Write contents of csv to .txt files with one file per row?

时间:2016-06-20 05:32:28

标签: python csv pandas dataframe

I have a csv in the following format:

0 | Hello
1 | Hi
2 | GoodDay

I need to copy each row to a text file, so output will be:

0.txt -> Hello
1.txt -> Hi
2.txt -> GoodDay

I try (edited):

df=pd.read_csv('result.csv')
for x in df.iterrows():
    pd.df([x[1][1]]).to_csv(str(x[1][0])+".txt", header=False, index=False)

I am using Python and Pandas.

1 个答案:

答案 0 :(得分:1)

首先按values转换为ndarray,然后使用tofile

for row in df.values:
    #print row
    row[1:].tofile(str(row[0])+'.txt', sep="\t", format="%s")

read_csv的解决方案:

import pandas as pd
import io

temp=u"""
0|Hello
1|Hi
2|GoodDay"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep="|", header=None)
print (df)
   0        1
0  0    Hello
1  1       Hi
2  2  GoodDay

for row in df.values:
    #print row
    row[1:].tofile(str(row[0])+'.txt', sep="\t", format="%s")

编辑:

包含iterrowsto_csv的另一个解决方案,但它在每个txt文件中添加了空行:

for _, s in df.iterrows():
    s.iloc[1:].to_csv(str(s.iloc[0]) + '.txt', index=False, header=False)