gpt4 book ai didi

python - 在 Python 中打印多个文件的特定行

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:57 25 4
gpt4 key购买 nike

我有 30 个文本文件,每个文件 30 行。出于某种原因,我需要编写一个脚本来打开文件 1、打印文件 1 的第 1 行、关闭它、打开文件 2、打印文件 2 的第 2 行、关闭它,等等。我试过这个:

import glob

files = glob.glob('/Users/path/to/*/files.txt')
for file in files:
i = 0
while i < 30:
with open(file,'r') as f:
for index, line in enumerate(f):
if index == i:
print(line)
i += 1
f.close()
continue

显然,我得到了以下错误:

ValueError:已关闭文件的 I/O 操作。

因为 f.close() 的事情。仅读取所需行后如何从一个文件移动到下一个文件?

最佳答案

首先,要回答问题,如评论中所述,您的主要问题是关闭文件然后尝试继续迭代它。有罪代码:

        for index, line in enumerate(f): # <-- Reads
if index == i:
print(line)
i += 1
f.close() # <-- Closes when you get a hit
# But loop is not terminated, so you'll loop again

最简单的解决方法是break 而不是显式关闭,因为您的with 语句已经保证在 block 退出时确定性关闭:

        for index, line in enumerate(f):
if index == i:
print(line)
i += 1
break

但是因为这很有趣,这里有一段经过显着清理的代码来完成相同的任务:

import glob
from itertools import islice

# May as well use iglob since we'll stop processing at 30 files anyway
files = glob.iglob('/Users/path/to/*/files.txt')

# Stop after no more than 30 files, use enumerate to track file num
for i, file in enumerate(islice(files, 30)):
with open(file,'r') as f:
# Skip the first i lines of the file, then print the next line
print(next(islice(f, i, None)))

关于python - 在 Python 中打印多个文件的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42239771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com