【发布时间】:2019-01-15 21:10:27
【问题描述】:
我想将一个(在现实生活中:巨大的)文件拆分为多个文件,这些文件由数据中的第二列指定。 IE。在下面的示例中,我需要文件 431.csv 和 rr1.csv。
我的主要想法是打开新连接以写入如果尚未打开 - 打开连接的记录在字典 files_dict 中,然后遍历它并最终关闭。
我被困在如何逐行引用这些连接。
在现实生活中,这些文件名(第二列)的数量和值是事先不知道的。
在这里找到了一些灵感:
write multiple files at a time
python inserting variable string as file name
How can I split a text file into multiple text files using python?
data_in中的玩具数据内容:
123,431,t
43,rr1,3
13,rr1,43
123,rr1,4
到目前为止我的幼稚伪代码:
files_dict = dict() #dict of file names
with open(data_in) as fi:
for line in fi:
x = line.split(',')[1]
if x not in files_dict:
fo = x + '.csv'
files_dict[x] = fo
'''
open files_dict[x]
write line to files_dict[x]
'''
else:
'''
write line to files_dict[x]
'''
for fo in files_dict.fos:
fo.close()
【问题讨论】:
-
您可以在 pandas 中用几行代码完成此操作。给我一秒钟写一个解决方案。或者其他人可能因为我在办公室。