python - 如何从文件中读取特定行(按行号)?

我正在使用 for 循环来读取文件,但我只想读取特定的行,例如行 #26#30。是否有任何内置功能可以实现这一点?

最佳答案

如果要读取的文件很大,并且您不想一次读取内存中的整个文件:

fp = open("file")
for i, line in enumerate(fp):
    if i == 25:
        # 26th line
    elif i == 29:
        # 30th line
    elif i > 29:
        break
fp.close()

注意 i == n-1 代表第 n 行。


在 Python 2.6 或更高版本中:

with open("file") as fp:
    for i, line in enumerate(fp):
        if i == 25:
            # 26th line
        elif i == 29:
            # 30th line
        elif i > 29:
            break

https://stackoverflow.com/questions/2081836/

相关文章:

python - 在python中将 float 转换为整数的最安全方法?

python - 如何在 Python 中将字符串转换为 double 值?

python - 输入()错误 - NameError : name '...' is not de

linux - 如何将命令行参数传递给 unix/linux 系统上正在运行的进程?

linux - 第一次如何配置postgresql?

linux - 如何规范化 Bash 中的文件路径?

python - 为什么需要在 Python 方法中显式使用 "self"参数?

python - Pandas :从多级列索引中删除一个级别?

linux - 如何获取进程 ID 以杀死 nohup 进程?

python - Google 大量使用 Python