[英]How to split CSV file into 2x separate CSV files based on values
我有一個CSV文件,其中包含我在四個星期內工作的日期。
文件有兩列[天,月]
26 8
27 8
28 8
29 8
30 8
31 8
1 9
2 9
3 9
4 9
5 9
6 9
7 9
如何將其寫入兩個新的CSV文件中,該文件在月底拆分。
我希望CSV_1的輸出如下:
26 8
27 8
28 8
29 8
30 8
31 8
我希望CSV_2的輸出如下:
1 9
2 9
3 9
4 9
5 9
6 9
7 9
這應該工作:
import csv
def write_new_file(data, file_counter):
with open(f'CSV_{file_counter}.csv', 'w', newline='') as new_csvfile:
writer = csv.writer(new_csvfile)
for new_row in new_data:
writer.writerow(new_row)
with open('csv.csv', newline='') as csvfile:
data = csv.reader(csvfile)
new_data = []
current_month = None
file_counter = 1
for row in data:
if current_month is None:
current_month = row[1]
if row[1] != current_month:
write_new_file(new_data, file_counter)
current_month = row[1]
file_counter += 1
new_data.clear()
new_data.append(row)
else:
write_new_file(new_data, file_counter)
可能會更短更甜,但是可以完成工作。 以防萬一,這也適用於任意月數的CSV文件,而不僅僅是2個月。
您可能需要更改輸入文件名。 現在,我將其設置為csv.csv
。 您可以添加input()
在運行時手動輸入文件名,而不是對其進行硬編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.