将每行迭代行写入文件而不覆盖python中的文件

时间:2016-08-26 08:38:03

标签: python python-2.7

我在Stackoverflow和本主题的所有“重复”上搜索了这个,但似乎仍然没有答案。我尝试了所有这些:

尝试#1:

for word in header:
    writer.writerow([word]

粘贴自writing data from a python list to csv row-wise

尝试#2:

而且这个应该已经接近但它有一个错误:

# Open a file in witre mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name


Pasted from <http://www.tutorialspoint.com/python/file_writelines.htm> 

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )

# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
   line = fo.next()
   print "Line No %d - %s" % (index, line)

# Close opend file
fo.close()

粘贴自http://www.tutorialspoint.com/python/file_writelines.htm

尝试3

>>>outF = open("myOutFile.txt", "w")
>>>for line in textList:
...    outF.write(line)
...    outF.write("\n")
>>>outF.close()

粘贴自http://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/

尝试#4:

with open('file_to_write', 'w') as f:
    f.write('file contents')

粘贴自Correct way to write line to file in Python

尝试#5:

这一个在写入文件时使用append ..但它在每行的末尾附加每一行。因此,我很难将所有行分开。

append_text = str(alldates)
with open('my_file.txt', 'a') as lead:
    lead.write(append_text)

粘贴自Python: Saving a string to file without overwriting file's contents

有人可以帮助我如何在循环中将每次迭代的行换行写入文件而不覆盖文件吗?

2 个答案:

答案 0 :(得分:0)

data = [1,2,3,4,5]
with open('asd.txt', 'w') as fn:
    for i in data:
        fn.write(str(i) + '\n') # Add a \n (newline) so the next write will occure in the next line

asd.txt的内容:

1
2
3
4
5

如果要附加到文件,请使用with open('asd.txt', 'a') as fn:

答案 1 :(得分:0)

有两种方法可以做到:

首先在输出行的末尾添加'\ n'字符:

for x in row:
   writer.write(x + "\n")

其次,在Append模式下打开文件,它会添加现有文本文件行,但要小心。它不会覆盖文件:

fw = open(myfile.txt,'a')