我正在尝试从同一行的两个不同文件中写两件事 一个不同的文件(即有3个文件正在使用.2个已经有项目和新文件)
fin=open("/Users/battledrum/Desktop/review2.txt")
fin1=open("/Users/battledrum/Desktop/review3.txt")
fout=open("/Users/battledrum/Desktop/HeightVStime.txt","w")
a=list()
for i in range(35):
fout.write(fin.read()+'\t'+fin1.read())
print(len(a))
这是我想在新文件中看到的结果:
1.34,1.54
1.80,1.39
1.25,1.68
1.69,1.83
答案 0 :(得分:1)
这有很多问题:
file.read()
获取文件的全部内容,因此您要编写(整个第一个文件)+ tab +(整个第二个文件),您希望逐行读取。
您永远不会追加到a
,因此len(a)
始终为0。
在a
- 逐行文件内容中,您是不是已经完全清楚了?
我想你想要更像
的东西HEIGHT_FILE = "/Users/battledrum/Desktop/review2.txt"
TIME_FILE = "/Users/battledrum/Desktop/review3.txt"
OUTPUT_FILE = "/Users/battledrum/Desktop/HeightVStime.txt"
def main():
# load data pairs
with open(HEIGHT_FILE) as hf, open(TIME_FILE) as tf:
hts = [(height.strip(), time.strip()) for height,time in zip(hf, tf)]
# write output
with open(OUTPUT_FILE, "w") as outf:
lines = ("{}\t{}".format(h, t) for h,t in hts)
outf.write("\n".join(lines))
print("{} lines written".format(len(hts)))
if __name__=="__main__":
main()
答案 1 :(得分:0)
不是在每个文件中假设一定数量的行,而是如下:
with open("/Users/battledrum/Desktop/HeightVStime.txt","w") as fout:
with open("/Users/battledrum/Desktop/review2.txt") as fin1:
with open("/Users/battledrum/Desktop/review3.txt") as fin2:
fout.writelines([(', '.join((x.rstrip('\n'),y))) for x,y in zip(fin1,fin2)])
zip
将合并fin1
和fin2
之间的行,因为我们可以将每个文件对象视为可迭代的,并且如果其中一个文件长于其他
答案 2 :(得分:0)
假设文件长度相同
with open(fin) as f1:
with open(fin1) as f2:
num1 = [l.strip() for l in f1.readlines()]
num2 = [l.strip() for l in f2.readlines()]
with open(fout,'w+') as out:
for i in range(0,len(num1)):
out.write(','.join([num1[i], num2[i]])+'\n')