我有两个小文件包含:
第1行f = 'employé numero 1'
等......
第1行的f2 = 'a'
等......
我想用f3写第一行:'雇员数字1 a'等
这是我的代码。执行后,没有错误消息,但f3仍为空:
f = open(r'c:\temp\merge1.txt','w',encoding='utf8')
for i in range(5): f.write(f"ligne {i+1}\n")
f.close()
f = open(r'c:\temp\merge1.txt','r',encoding='utf8')
f2 = open(r'c:\temp\merge2.txt','w',encoding='utf8')
for i in range(5): liste = ['a','b','c'] f.write(liste[i] "\n")
f2.close()
f2 = open(r'c:\temp\merge2.txt','r',encoding='utf8')
f3 = open(r'c:\temp\merge3.txt','w',encoding='utf8')
for line in f:
line_liste = line.split()
for line2 in f2:
line2_liste = line2.split()
line_liste.append(line2_liste)
f3.write(",".join(line_liste))
答案 0 :(得分:0)
您在上面发布的代码的第一部分中有几处错误。我猜这是一个复制/粘贴问题。
例如,这里我上升到5但是只有3个项目。这会导致错误。
for i in range(5):
liste = ['a','b','c']
f.write(liste[i] "\n")
我重写了for循环。很高兴看到一个完整的输出示例,但如果我理解的话,这就是你要找的东西。
for line in f:
line_liste = line.split()
for line2 in f2:
output_line = '{} {}'.format(line_liste[0], line2)
f3.write(output_line)
merge3.txt的内容
ligne a
ligne b
ligne c
答案 1 :(得分:0)
>>> f = open(r'c:\temp\merge1.txt','w',encoding='utf8')
>>> for i in range(5):
f.write(f"ligne {i+1}\n")
>>> f.close()
>>> f = open(r'c:\temp\merge1.txt','r',encoding='utf8')
>>> f2 = open(r'c:\temp\merge2.txt','w',encoding='utf8')
>>> for i in range(5):
liste = ['a','b','c']
f.write(liste[i] "\n")
>>> f2.close()
>>> f2 = open(r'c:\temp\merge2.txt','r',encoding='utf8')
>>> f3 = open(r'c:\temp\merge3.txt','w',encoding='utf8')
>>> for line in f:
line_liste = line.split()
for line2 in f2:
line2_liste = line2.split()
line_liste.append(line2_liste)
f3.write(",".join(line_liste))
>>> f3.close()