编写 CSV 文件时如何避免多余的空行?

1 python csv newline

我有以下代码,我只是希望它将列表写入文件。它这样做了,但每次都有一个空行,这会导致每次迭代出现问题!

with open("films.txt", mode='r') as f:
 allfilms=[]

 reader = csv.reader(f)
 for row in reader:
    #create a list again which reads in and stores all films in the file

    allfilms.append(row)
    print(allfilms)


with open("films.txt","w") as f:
     writer=csv.writer(f)
     writer.writerows(allfilms)
Run Code Online (Sandbox Code Playgroud)

输出为:0、流派、标题、评级、喜欢

    1,Sci-Fi,Out of the Silent Planet, PG, 0

    2,Sci-Fi,Solaris, PG,0

    3,Sci-Fi,Star Trek, PG, 0

    4,Sci-Fi,Cosmos, PG, 0
Run Code Online (Sandbox Code Playgroud)

如前所述,我不想在保存列表时出现空行。另外,我对做同样事情的更优雅或更好的方法感兴趣。我希望将文件读入列表,然后写回文件,在格式方面与文件中存储的内容完全相同。

提前致谢

Blu*_*ode 10

我相信您问题的根源在于,当您打开 时films.txt,您忘记了newline=''按照文档所说使用的参数。这意味着您的代码将变为:

with open("films.txt", mode='r', newline='') as f:
Run Code Online (Sandbox Code Playgroud)

with open("films.txt", mode='w', newline='') as f:
Run Code Online (Sandbox Code Playgroud)