我的目标是打开一个非常大的 csv 文件,读取该文件,然后对数据子集进行处理。在这种情况下,“东西”正在写入一个空白的 csv,但将来它将在数据上运行函数,一次 200 行(由于某种原因,这节省了我的计算时间,通过功能)。
我当前的问题是,当我编写空白csv时,如果我使用
header = False
,我没有标题,但如果我取出该命令,我每200行就有一个标题。如果可能的话,我希望标题位于顶部一次?
with open(csvFile, encoding = 'utf8', errors = 'ignore') as csv_file:
chunksize = 200
i = 0
j = 1
for df in pd.read_csv(csv_file, encoding = 'utf-8', chunksize=chunksize, iterator=True):
df.index += j
i+=1
df.to_csv('test.csv', mode = 'a', sep = ',', encoding='utf-8', header=False, index=False)
j = df.index[-1] + 1
第一次写的时候就写上
header=True
。
with open(csvFile, encoding = 'utf8', errors = 'ignore') as csv_file:
chunksize = 200
i = 0
j = 1
for df in pd.read_csv(csv_file, encoding = 'utf-8', chunksize=chunksize, iterator=True):
df.index += j
i += 1
if i == 1:
df.to_csv('test.csv', mode = 'w', sep = ',', encoding='utf-8', header=True, index=False)
else:
df.to_csv('test.csv', mode = 'a', sep = ',', encoding='utf-8', header=False, index=False)
j = df.index[-1] + 1
你可以
import os
并使用,我没有写你所有的代码,但主要依据是
if os.path.exists(csv_file):
headers=false
else:
headers=true
只需创建一个 CSV 文件并插入所需的标题即可。例如:
some,kind,of,header,content
稍后当您插入数据框时,您将不需要通过代码创建标题。