我正在处理几百个文本文件(1.txt,2.txt,3.txt ...)形式的光谱数据,它们的格式都完全相同,如下所示:为了清楚起见:1.txt: 2.txt: 3.txt:1,5 1,4 1,72,8 2,9 2,143,10 3,2 3,54,13 4,17 4,9<...> <...> <...>4096,1 4096,7 4096,18我试图逐行连接它们,所以我走开了一个输出文件,例如:5,4,78,9,1410,2,513,17,9<...>1,7,18我是Python的新手,非常感谢您的帮助。我尝试过这种混乱:howmanyfiles=8output=open('output.txt','w+')for j in range(howmanyfiles): fp=open(str(j+1) + '.txt','r') if j==0: for i, line in enumerate(fp): splitline=line.split(",") output.write(splitline[1]) else: output.close() output=open('output.txt','r+') for i, line in enumerate(fp): splitline=line.split(",") output.write(output.readline(i)[:-1]+","+splitline[1]) fp.close()output.close()我在上面的思路是,我需要将光标放回到每个文件的文档开头。
2 回答
繁华开满天机
TA贡献1816条经验 获得超4个赞
我认为您可以从zip内置函数中受益匪浅,它将使您可以同时遍历所有输入文件:
from contextlib import ExitStack
num_files = 8
with open("output.txt", "w") as output, ExitStack() as stack:
files = [stack.enter_context(open("{}.txt".format(i+1)))
for i in range(num_files)]
for lines in zip(*files): # lines is a tuple with one line from each file
new_line = ",".join(line.partition(',')[2] for line in lines) + "\n"
file.write(new_line)
添加回答
举报
0/150
提交
取消