用Python编写CSV文件

时间:2013-01-26 17:50:32

标签: 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
         ..."

正如你所看到的那样,数据是由一个空格字符分隔的(并且连续有5个“文本”(我的意思是字符串)。我想写一个CSV表来使数据看起来不错。所以它看起来像那样:

 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列,每个字符串应该在一个单元格中。 我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

你试试这个

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()

答案 1 :(得分:1)

此代码会将数据写入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