【发布时间】:2016-08-26 08:38:03
【问题描述】:
我已经在 Stackoverflow 上搜索了这个以及该主题的所有“重复项”,但似乎仍未得到答复。这些我都试过了:
尝试#1:
for word in header:
writer.writerow([word]
从writing data from a python list to csv row-wise粘贴em>
尝试#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粘贴em>
尝试#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粘贴em>
尝试#5:
这个在写入文件时使用附加..但它在每一行的末尾附加每一行。所以我很难把所有的行分开。
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粘贴em>
谁能帮我在不覆盖文件的情况下,如何在循环中每次迭代将换行的行写入文件?
【问题讨论】:
-
是否要在文件中添加换行符 (\n) 而不是覆盖它?stackoverflow.com/questions/4706499/…
-
'append' 只会在另一行的末尾写一行..所以处理数据会非常困难..因为它们没有分开
-
追加时可以添加自己想要的分隔符
-
是的..我做到了..谢谢..问题解决了。
标签: python python-2.7