【问题标题】:Writing a line of row per iteration to file without overwriting the file in python每次迭代将一行写入文件而不覆盖python中的文件
【发布时间】: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


【解决方案1】:
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:

【讨论】:

  • 是否可以在每次迭代时将一行写成新行?
  • 使用前导 '\n' 而不是尾随 '\n': fn.write('\n'+str(i))
【解决方案2】:

有两种方法可以做到这一点:

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

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

第二次以追加模式打开文件,它将添加现有文本文件的行,但要小心。它不会覆盖文件:

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

【讨论】:

  • 是的,我已经尝试过这些,但附加只会在另一行的末尾添加一行。因此,如果我有数千个数据,就很难分离数据
  • 不能分隔行是什么意思??
  • 您的代码实际上与 'a' 和 '\n' 一起使用,以便在循环中每次迭代写入行。谢谢! ...但我没有使用 for-loop 'for x in row:'
猜你喜欢
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 2023-03-28
  • 2014-12-28
  • 1970-01-01
  • 2011-05-08
  • 2014-02-05
  • 1970-01-01
相关资源
最近更新 更多