简体   繁体   English

在python中合并文件时,csv中双引号不断出现,如何删除?

[英]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. 我有许多带有URL链接的文件,我想将它们全部合并为一个大文件。 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). 合并后的文件以某种方式在最终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. 我阅读了python的csv模块文档,并添加了“ writeFile = csv.QUOTE_NONE”行,但这没什么区别。

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). 现在看来这行之有效,需要一行来删除不必要的,添加的双引号(隐藏且仅在每个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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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