简体   繁体   English

不使用换行符Python将列表写入文件

[英]Writing a list to a file without a newline Python

I have the following code, and I simply want it to write the list to a file. 我有以下代码,我只希望它将列表写入文件。 It does so, but with a blank line each time, which causes problems with every iteration! 这样做,但是每次都有一个空行,这会导致每次迭代都出现问题!

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)

The output is: 0,Genre, Title, Rating, Likes 输出为: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

As mentioned, I don't want the blank line when saving the list. 如前所述,在保存列表时,我不需要空白行。 Also, I'd be interested in more elegant or better ways of doing the same thing. 另外,我会对更优雅或更佳的方式做同一件事感兴趣。 I want the file to be READ in to the list, and then written back to the file EXACTLY the same, in terms of formatting, as what was stored in the file. 我希望将文件读入列表,然后再将其写回到文件,就格式而言,它与文件中存储的内容完全相同。

Thanks in advance 提前致谢

Edit: I misunderstood how the csv module gave output when I wrote this answer, but I am not removing it due to the helpful comment by downshift on it. 编辑:我误解了csv模块在编写此答案时是如何输出的,但是由于降级对它有帮助,因此我没有删除它。 Please see my more recent and more accurate answer. 请查看我最近的更准确的答案。

downshift answered this in the comments, but I will try to give a little more detail about why this is happening. 降档在评论中回答了这个问题,但我将尝试提供更多有关为什么发生这种情况的详细信息。

When you read each row in from the csv reader, it gives you the entire row, which includes the newline character ( \\n ) at the end. 当您从csv阅读器中读取每一行时,它会为您提供整行,并在末尾包含换行符( \\n )。 Your issue stems from the fact that when you write to the file, the write function adds it's own newline character to the end of your string. 您的问题源于以下事实:写入文件时,write函数将其自己的换行符添加到字符串的末尾。 Luckily there are two very simple ways to remove the newline character from the end of the line you get back from the csv reader. 幸运的是,有两种非常简单的方法可以从csv阅读器返回的行尾删除换行符。

One way is to use the .strip() method of a string, which takes in some characters in the form of a string as input, and strips of as many of those characters as possible from the ends of the string. 一种方法是使用字符串的.strip()方法,该方法以字符串形式输入一些字符作为输入,并从字符串的.strip()尽可能多的这些字符。 Using this method you could replace: 使用此方法,您可以替换:

allfilms.append(row)

with

allfilms.append(row.strip("\n"))

Another way you could do it is to use string slicing and slice off the last character of the string. 您可以执行的另一种方法是使用字符串切片并切掉字符串的最后一个字符。 I wouldn't recommend you use string slicing for this, because it is less clear what you are doing, but if you wanted to, you would replace: 我不建议您为此使用字符串切片,因为不清楚您在做什么,但是如果您愿意,可以替换为:

allfilms.append(row)

with

allfilms.append(row[:-1])

row[:-1] will return row with the last character excluded, discarding the newline character. row[:-1]将返回不包含最后一个字符的row,并丢弃换行符。

Hope this helped you! 希望这对您有所帮助!

I believe the source of your issue is that when you opened films.txt , you forgot to include the newline='' argument as the docs say to use. 我相信问题的根源是,当您打开films.txt ,您忘了像文档所说使用的那样包含newline=''参数。 This means your code becomes: 这意味着您的代码变为:

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

and

with open("films.txt", mode='w', newline='') as f:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM