[英]How to split each value in a column as a seperate csv file in Python?
我在csv文件中有一个像这样的列:
-----
label
-----
0
1
0
2
1
4
3
0
现在,我需要将每个值写为不同的CSV文件,即:
0.csv
1.csv
...
7.csv
我已经尝试了下面的代码,可以将每一行写在单个csv文件中:
import re
test_f = open('test.csv')
result_f = open('result.csv', 'a')
for line in test_f:
new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
result_f.write(new_str)
# also, this too, please:
test_f.close()
result_f.close()
但是我不知道如何将每一行保存在不同的文件中。 有什么更好的建议吗?
这个代码怎么样? 它已经使用上下文管理器(with)为您处理了“关闭”方法,跳过了标头并将内容拆分为文件,并拆分为具有单独关注点的函数! ;)
import re
def skip_header(source):
for i in range(3):
next(source)
def write_file(filename, content):
print(f'Writting file "{filename}" with content "{content}"...')
with open(filename, 'w') as destination:
destination.write(content)
src_filename = './csv/main.csv'
with open(src_filename) as source:
skip_header(source)
for index, line in enumerate(source):
dst_filename = f'./csv/file_{str(index)}.csv'
content = re.sub('[^a-zA-Z0-9\.]', "", line)
write_file(dst_filename, content)
这是简单项目的文件夹结构。 文件file_X.csv是由上面的代码(Python 3.6.4)生成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.