字符串输出中的CSV文件

时间:2017-03-16 13:01:20

标签: python csv dataframe jupyter-notebook

我有这种字符串输出:

Gender,Age,Weight,Height
Male, 55, 82, 180
Female, 34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185

从此输出制作CSV文件的最简单方法是什么?我尝试了一些StringIO方法,但我无法在Python 3.6.0中使用它们。

4 个答案:

答案 0 :(得分:3)

假设您在列表中包含此字符串,为什么不直接写入文件

>>> f = file('test.csv', 'w')
>>> lines = [ 'Gender,Age,Weight,Height',
    'Male, 55, 82, 180',
    'Female, 34,55,167',
    'Female,44,67,182',
    'Male,81,73,175',
    'Male,44,34,87,185']
>>> f.write('\n'.join(lines))
>>> f.flush()
>>> f.close()

答案 1 :(得分:3)

第一种方法:使用StringIO

这是我的方法,我针对Python 3.6进行了测试:

import csv
from io import StringIO

my_string = """
Gender,Age,Weight,Height
Male, 55, 82, 180
Female, 34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185
"""

buffer = StringIO(my_string)

reader = csv.reader(buffer, skipinitialspace=True)
with open('string2csv.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    writer.writerows(reader)

string2csv.csv文件的内容:

Gender,Age,Weight,Height
Male,55,82,180
Female,34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185

注释

  • 由于输入字符串在逗号后面有空格(换句话说,是条目前的初始空格),我使用skipinitialspace=True参数来删除这些空格。
  • 使用writerows(复数)代替writerow(单数),我可以编写更少的代码

第二种方法:分割线

如果您不想使用StringIO,那么我们可以拆分行,将它们输入csv.reader并获得相同的结果:

my_string = """
Gender,Age,Weight,Height
Male, 55, 82, 180
Female, 34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185
"""
reader = csv.reader(my_string.splitlines(), skipinitialspace=True)
with open('string2csv.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    writer.writerows(reader)

答案 2 :(得分:0)

  

我有这种字符串输出。

我们假设字符串名称是data

import StringIO
import csv

data = """Gender,Age,Weight,Height
Male, 55, 82, 180
Female, 34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185"""

f = StringIO.StringIO(data)
reader = csv.reader(f, delimiter=',')

myfile = open('output.csv', 'wb')
writer = csv.writer(myfile, quoting=csv.QUOTE_ALL)

for row in reader:
    print '\t'.join(row)
    writer.writerow(row)

答案 3 :(得分:0)

您可以使用pandas和数据框来执行此操作:

df = { 'Gender' : pd.Series(['Male', 'Female', 'Female', 'Male', 'Male']), 
       'Age' : pd.Series([55, 34, 44, 81, 44]), 
      'Weight' : pd.Series([82, 55, 67, 73, 87]), 
      'Height' : pd.Series([180, 167, 182, 175, 185])}
df = pd.DataFrame(df)

df.to_csv('my_file.csv', '\t')