用Python编写CSV文件
我有一个字符串,看起来像这样:用Python编写CSV文件,python,csv,Python,Csv,我有一个字符串,看起来像这样: text = "Text1 Text2 Text3 Text4 Text5\n Here comes more test text\n and even more1 more2 more3\n tex text textt te tex\n 1 2 3 4 5 ..." Col1 2 3 4 5 Text1 Text2 Text3 Tex
text = "Text1 Text2 Text3 Text4 Text5\n
Here comes more test text\n
and even more1 more2 more3\n
tex text textt te tex\n
1 2 3 4 5
..."
Col1 2 3 4 5
Text1 Text2 Text3 Text4 Text5
Here comes more test text
and even more1 more2 more3
tex text textt te tex
1 2 3 4 5
如您所见,数据由一个空格字符分隔(一行中正好有5个“文本”(我是指字符串)。我想编写一个CSV表,使数据看起来更漂亮。因此,它看起来像:
text = "Text1 Text2 Text3 Text4 Text5\n
Here comes more test text\n
and even more1 more2 more3\n
tex text textt te tex\n
1 2 3 4 5
..."
Col1 2 3 4 5
Text1 Text2 Text3 Text4 Text5
Here comes more test text
and even more1 more2 more3
tex text textt te tex
1 2 3 4 5
应该有5列,每个字符串应该在一个单元格中。
我该怎么做呢?你试试这个
text = "Text1 Text2 Text3 Text4 Text5\n\
Here comes more test text\n\
and even more1 more2 more3\n\
tex text textt te tex\n\
1 2 3 4 5"
filecsv = open('csvfile.csv', 'w+')
filecsv.write(text.replace(' ', ';'))
filecsv.close()
此代码将数据写入
csv
文件
text = """Text1 Text2 Text3 Text4 Text5\n
Here comes more test text\n
and even more1 more2 more3\n
tex text textt te tex\n
1 2 3 4 5"""
data = [x.strip() for x in text.split("\n") if x.strip() != ""]
columns = ["Col1", "2", "3", "4", "5"]
# Write dictionary list to file
outfile = "d2.csv"
with open(outfile, "w") as fp:
for key in columns:
fp.write(key + ", ")
fp.write("\n")
for line in data:
l = ", ".join(line.split())
print l
fp.write(l)
fp.write("\n")
输出:
Col1, 2, 3, 4, 5,
Text1, Text2, Text3, Text4, Text5
Here, comes, more, test, text
and, even, more1, more2, more3
tex, text, textt, te, tex
1, 2, 3, 4, 5
您自己尝试过任何东西吗?您看到python了吗?在我看来,您更想要一个固定列宽的输出表--您的输出分隔符宽度在列之间变化。第一步:
table=[line.split()表示文本中的行。split('\n')]
。不客气:)您正在寻找显示在屏幕上的数据或写入实际的.csv文件吗?您的示例输出实际上不是csv,因此我不清楚您真正想要的是什么。这不会生成csv文件。你是说filecsv.csv
和,
而不是代码>?这对我有用。谢谢我喜欢它,它很轻-但它的“.csv”