gpt4 book ai didi

python - 同时读取多个文件的每一行

转载 作者:行者123 更新时间:2023-12-01 02:34:39 38 4
gpt4 key购买 nike

我的文件夹中有“n”个“.txt”文件,我想同时打开它们并循环读取每个文件的第一行,然后每隔一行......

我的文件是这样写的:

0
1
0
1
1
0
0
0

我用过

file = fileinput.input(files=("text_{}.txt".format(i)))
for line in file:
for ch in line:
print file.readline()

谢谢

最佳答案

如果你不想读取内存中每个文件的内容,

FILES = ['1.txt', '2.txt', '3.txt']

if __name__ == '__main__':
file_handles = {filename: open(filename, 'r') for filename in FILES}
while 1:
for filename, file in file_handles.items():
line = next(file, None)
if line is not None:
line = line.rstrip('\n')
print(line)
else:
file.close()
# file_handles.pop(filename)
if line is None:
break

关于python - 同时读取多个文件的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391572/

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