简体   繁体   中英

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:

-----
label
-----
0
1
0
2
1
4
3
0

Now I need to write each value as a different CSV files that is:

0.csv
1.csv
...
7.csv

I have tried with the folowing code that can write each line on a single csv file:

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! ;)

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).

项目文件夹结构

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM