簡體   English   中英

如何在Python中將列中的每個值拆分為單獨的CSV文件?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM