简体   繁体   中英

Double quotes keep coming in csv when merging file in python, how to remove?

I have many files with URL links and I want to merge them all into one big file. The links in the inidividual files do not have double quotes around them. The merged file somehow added double quote to each link in the final csv (MergedURLs.csv). I read up the csv module documentation for python, and added the line "writeFile = csv.QUOTE_NONE", but it made no difference.

import csv

def mergeFile(a, b, x, y):
    for loop1 in range(a, b):
        for loop2 in range(x, y):
            try:
                fileName1 = "FoundValidURLs_"
                fileName2 = "_"
                fileName3 = ".csv"
                fileNameComplete = fileName1 + str(loop1) + fileName2 + str(loop2) + fileName3

                with open(fileNameComplete, "rb") as f:
                    for URLrecords in f: 
                        with open("MergedURLs.csv", "ab") as fi:
                            writeFile = csv.writer(fi)
                            writerFile = csv.QUOTE_NONE
                            writeFile.writerow([URLrecords])

            except IOError:
                continue
            loop2 += 1
        loop1 += 1

mergeFile(1, 2, 1, 3)

This seems to be working now, a line is needed to remove the unnecessary, added double quote (hidden and only at the end of each url).

with open(fileNameComplete, "rb") as f:
    for URLrecords in f: 
        with open("MergedURLs.csv", "ab") as fi:
            writeFile = csv.writer(fi)
            URLrecords_strip = URLrecords[0:-1] # strip away the quotation at the end
            writeFile.writerow([str(URLrecords_strip)])

您需要将csv.QUOTE_NONE作为参数传递给csv.QUOTE_NONE ,而不是分配给单独的变量:

writeFile = csv.writer(fi, quoting=csv.QUOTE_NONE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM