我编写了代码以产生以下输出。当我在代码中的标记行中使用追加功能时,它工作正常,但是当我使用“ w”写入功能时,它仅在新创建的文本文件中打印一行。使用append函数的问题是,如果我们再次运行代码,它将两次复制相同的输出。我无法理解这一点。请先帮助谢谢
我使用的代码:
import os
with open("input5.csv", 'r+') as fd:
lines = fd.readlines()
fd.seek(0)
fd.writelines(line for line in lines if line.strip())
fd.truncate()
lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])
with open('output1.txt', 'r+') as m:
newText = m.read()
while ',' in newText:
newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
m.write(newText)
with open("output1.txt","r+") as fp:
for cnt, line in enumerate(fp):
line=line.replace('_',',',3)
print(line)
f = open('output7.txt', 'a') #THIS LINE
for i in range(len(line)):
f.write((line[i]))
f.close()
os.remove("output1.txt")
输入:
id,name,amount,subject
1,abc,55,"s1,s2,s3"
1,abc1,56,"s4,s5,s6"
1,abc2,57,"s7,s8,s9"
1,abc3,58,"s10,s11,s12"
1,abc4,59,"s13,s14,s15"
1,abc5,59,"s16,s17,s18"
1,abc6,59,"s13,s14,s15"
1,abc7,59,"s13,s14,s15"
1,abc8,59,"s13,s14,s15"
1,abc9,59,"s13,s14,s15"
this file is done
time taken; 22nd
预期输出:(这是我在使用附加功能标记的代码行时得到的代码)
1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"
1,abc8,59,"s13_s14_s15"
1,abc9,59,"s13_s14_s15"
当我用标记的代码行中的write函数替换append时得到的输出:
1,abc9,59,"s13_s14_s15"
答案 0 :(得分:1)
类似这样的事情(未经测试),其中打开和关闭文件的位置不在循环之内:
import os
with open("input5.csv", 'r+') as fd:
lines = fd.readlines()
fd.seek(0)
fd.writelines(line for line in lines if line.strip())
fd.truncate()
lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])
with open('output1.txt', 'r+') as m:
newText = m.read()
while ',' in newText:
newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
m.write(newText)
with open("output1.txt","r+") as fp:
f = open('output7.txt', 'w') #THIS LINE
for cnt, line in enumerate(fp):
line=line.replace('_',',',3)
print(line)
for i in range(len(line)):
f.write((line[i]))
f.close()
os.remove("output1.txt")
答案 1 :(得分:1)
On my machine (Ubuntu 18.04) with python 3.6.7
your example works as expected.
output7.txt
contains
1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"
So, the write
function does work properly. However, it is a good question, why doesn't it work for you.