在分割CSV文件时从前端和后端删除双引号

2024-06-06 20:08:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用大型CSV文件。我能够编写一个代码,将文件分成小块:

import csv

divisor = 500000

outfileno = 1
outfile = None

with open('testM.txt', 'r') as infile:
    infile_iter = csv.reader(infile)
    header = next(infile_iter)
    for index, row in enumerate(infile_iter):
        if index % divisor == 0:
            if outfile is not None:
                outfile.close()
            outfilename = 'big-{}.csv'.format(outfileno)
            outfile = open(outfilename, 'w')
            outfileno += 1
            writer = csv.writer(outfile)
            writer.writerow(header)
        writer.writerow(row)

    if outfile is not None:
        outfile.close()

我面临的问题是,拆分后生成的第一个csv的所有行的开头和结尾都有双引号。其余的CSV文件没有这个双引号问题。而且,原始文件没有任何双引号。你知道吗

Example, the first csv file looks something like below:
"abc,ghhh,123,fgfg"
"hjfhj,12312,adfa,6765"

这导致了一个问题,因为我必须在它们上面运行更多的测试,第一个文件导致了这个问题,而其余的都很好。如果有人能帮我修改这段代码来解决我的问题,那会很有帮助。你知道吗


Tags: 文件csv代码noneifopeninfileoutfile
2条回答

快速浏览CSV模块将有您的问题的答案。你知道吗

https://docs.python.org/3/library/csv.html#csv.QUOTE_NONE

您可以使用Pandas修复输入并使逻辑更加简单。你知道吗

import csv
import pandas as pd

filename='big-'
for count, chunk in enumerate(pd.read_csv(filename, delimiter=",", quoting=csv.QUOTE_NONE, encoding='utf-8', iterator=True, chunksize=50000)):
    #fix the 1 and N columns to remove the doublequotes char
    chunk[chunk.columns[0]]=chunk[chunk.columns[0]].str[1:]
    chunk[chunk.columns[-1]]=chunk[chunk.columns[-1]].str[:-1]
    #change these columns datatypes if necessary/useful
    #put in the rest of your logic here (saving files etc..)
    chunk.to_csv(file_name+'{}'.format(count))

*警告:我尚未测试整个解决方案。所以你的里程数可能会有所不同。你知道吗

感谢@code mocker的报价。你知道吗

相关问题 更多 >