[英]I want to save a List in a .csv file. Every \n in the list should make a new line in the file
Example list:示例列表:
line = ['New York;New\nBerlin;Ber\nMelbourne;Mel']
Every second element in my list contains a \n.我列表中的每个第二个元素都包含一个 \n。
with open('file.csv', 'w', newline='') as csvfile:
save = csv.writer(csvfile)
y = list.count("\n")
for line in range(0, y):
save.writerow(str(list))
How the.csv file should look like: .csv 文件应如下所示:
NewYork;New
Berlin;Ber
Melbourne;Mel
My Goal is to display the list in excel.我的目标是在 excel 中显示列表。 This should look like this:
这应该是这样的:
New York |纽约 | New
新的
Berlin |柏林 | Ber
贝尔
Melbourn |墨尔本 | Mel
梅尔
| | = new colum
= 新列
How does the saving process needs to look like?保存过程需要是什么样的?
Your list is not a Python list it should be something like this, if it contains one string with \n
in it.您的列表不是 Python 列表,如果它包含一个带有
\n
的字符串,它应该是这样的。
lines = ["New York;New\nBerlin;Ber\nMelbourne;Mel"]
or like this if it contains multiple strings with '\n' in it或者如果它包含多个带有 '\n' 的字符串,则像这样
lines = ["New York;New\nBerlin;Ber\nMelbourne;Mel",
"Ber\nMelbourne;Mel\nNew York;New\nBerlin",
...
]
Also it is not very clear what you are trying to achieve from the code you have written, but the question seems to be that you have a list of strings with new line characters in it, and you want to break the line at '\n' while writing it to a csv file.此外,还不是很清楚您要从您编写的代码中实现什么,但问题似乎是您有一个包含换行符的字符串列表,并且您想在 '\n 处换行' 同时将其写入 csv 文件。
the code for which is quite simple代码很简单
import csv
# this list is explained above
lines = ["New York;New\nBerlin;Ber\nMelbourne;Mel", "New York;New\nBerlin;Ber\nMelbourne;Mel"]
lines = [[word] for line in lines for word in line.split('\n')]
with open('file.csv', 'w') as fh:
csv_writer = csv.writer(fh)
csv_writer.writerows(lines)
Additionally since you did not talk about columns, I would suggest please read on CSV files, you might not need a CSV file.此外,由于您没有谈论专栏,我建议您阅读 CSV 文件,您可能不需要 CSV 文件。
after reading your comment, I believe you have one big string of content, and the changing first two lines in above code to this should work.阅读您的评论后,我相信您有一大串内容,并且将上述代码中的前两行更改为此应该可以工作。
content = "first colum first line; second colum first line \n first colum second line; second colum second line"
lines = [line.split(';') for line in content.split('\n')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.