有個任務,就是將一個大的csv分割爲幾個小的csv,當然是的包飯表頭的。
於是,我想到了類似於,用雙指針來做。
import csv
import os
path = '/Users/mac/Desktop/186_3.csv'
with open(path, 'r', newline='') as file:
csvreader = csv.reader(file)
a = next(csvreader)
print(a)
i = j = 1
for row in csvreader:
print(row)
print(f'i is {i}, j is {j}')
# 沒1000個就j加1, 然後就有一個新的文件名
if i % 1000 == 0:
j += 1
print(f"csv {j} 生成成功")
csv_path = os.path.join('/'.join(path.split('/')[:-1]), '186_3/' + str(j) + '.csv')
# print('/'.join(path.split('/')[:-1]))
print(csv_path)
# 不存在此文件的時候,就創建
if not os.path.exists(csv_path):
with open(csv_path, 'w', newline='') as file:
csvwriter = csv.writer(file)
csvwriter.writerow(['image_url'])
csvwriter.writerow(row)
i += 1
# 存在的時候就往裏面添加
else:
with open(csv_path, 'a', newline='') as file:
csvwriter = csv.writer(file)
csvwriter.writerow(row)
i += 1