【问题标题】:Write contents of csv to .txt files with one file per row?将 csv 的内容写入 .txt 文件,每行一个文件?
【发布时间】:2016-06-20 05:32:28
【问题描述】:

我有一个格式如下的 csv:

0 | Hello
1 | Hi
2 | GoodDay

我需要将每一行复制到一个文本文件中,所以输出将是:

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

我尝试(已编辑):

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)

我正在使用 Python 和 Pandas。

【问题讨论】:

  • 标签似乎匹配,语言和模块的选择看起来不错。但是您尝试的代码丢失了(您已经在使用 Python 和 Pandas ... ;-)。请添加到问题中,以便我们提供帮助。谢谢。

标签: python csv pandas dataframe


【解决方案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)

【讨论】:

  • 谢谢!!像魅力一样工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多