python 不追加每行但跳过一些

python doesn't append each line but skips some

我有一个 complete_list_of_records 长度为 550

这个列表看起来像这样:

  1. 苹果

  2. 香蕉

问题是当我使用:

 with open("recordedlines.txt", "a") as recorded_lines:
      for i in complete_list_of_records:
            recorded_lines.write(i)

文件的结果是 393 长,有些地方的结构看起来像这样

  1. 苹果

  2. 梨香蕉

  3. 菠萝

我尝试使用 "w" 而不是 "a" 附加并手动插入 "\n" 列表中的每个项目,但这只会在每隔一行创建空格,并且仍然有一些行双线合一也有同样的问题。

有谁遇到过类似的情况吗?

在任何情况下,您都可以简单地删除所有空格,然后像这样每手插入一个换行符:

with open("recordedlines.txt", "a") as recorded_lines:
    for i in complete_list_of_records:
        recorded_lines.write(i.strip() + "\n")

[索恩][1]

complete_list_of_records =['1.Apples','2.Pears','3.Bananas','4.Pineapples']

with open("recordedlines.txt", "w") as recorded_lines:
      for i in complete_list_of_records:
            recorded_lines.write(i+"\n")

我认为它应该有效。 确保你写成一个字符串。

你需要使用

file.writelines(listOfRecords)

但列表值必须有'\n'

f = open("demofile3.txt", "a")
li = ["See you soon!", "Over and out."]
li = [i+'\n' for i in li]
f.writelines(li)
f.close()

#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())

输出将是

See you soon!
Over and out.

您还可以使用 for 循环,write() 在每次迭代时都有 '\n'

从目前看到的评论来看,我认为源列表中有些字符串在末尾以外的位置包含换行符。另外,似乎有些字符串以换行符结尾,但不是全部。

我建议用其他字符替换嵌入的换行符 - 例如下划线。

因此我建议:

with open("recordedlines.txt", "w") as recorded_lines:
      for line in complete_list_of_records:
            line = line.rstrip() # remove trailing whitespace
            line = line.replace('\n', '_') # replace any embedded newlines with underscore
            print(line, file=recorded_lines) # print function will add a newline