[英]How to split each value in a column as a seperate csv file in Python?
I have a column like this in a csv file: 我在csv文件中有一个像这样的列:
-----
label
-----
0
1
0
2
1
4
3
0
Now I need to write each value as a different CSV files that is: 现在,我需要将每个值写为不同的CSV文件,即:
0.csv
1.csv
...
7.csv
I have tried with the folowing code that can write each line on a single csv file: 我已经尝试了下面的代码,可以将每一行写在单个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()
But I don't know how to save each line in a different file. 但是我不知道如何将每一行保存在不同的文件中。 Any better sugestion, please?
有什么更好的建议吗?
How about this code? 这个代码怎么样? It already handles the "close" methods for you using context managers (with), skips the header and split the content into files and is splited into functions with separate concerns!
它已经使用上下文管理器(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)
Here is the folder structure of the simple project. 这是简单项目的文件夹结构。 The files file_X.csv were generated by the code above (Python 3.6.4).
文件file_X.csv是由上面的代码(Python 3.6.4)生成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.