Python - Spyder 3 - 打开 .csv 文件列表并删除每个文件中的所有双引号

Python - Spyder 3 - Open a list of .csv files and remove all double quotes in every file

我已经阅读了所有我能找到的东西,并尝试了来自 SO 和 google 的大约 20 个示例,但似乎没有任何效果。

这应该很简单,但我无法让它工作。我只想指向一个文件夹,并替换文件夹中每个文件中的每个双引号。这就对了。 (而且我根本不了解 Python,因此我的问题。)我毫不怀疑我尝试重新分配的一些脚本必须有效,但我缺乏 Python 技能是妨碍。这和我得到的一样接近,但我得到了错误。如果我没有收到错误,它似乎什么都不做。谢谢

import glob
import csv

mypath = glob.glob('\C:\csv\*.csv')

for fname in mypath:
    with open(mypath, "r") as infile, open("output.csv", "w") as outfile:
        reader = csv.reader(infile)
        writer = csv.writer(outfile)
    for row in reader:
        writer.writerow(item.replace("""", "") for item in row)

您不需要使用特定于 csv 的文件打开和写入,我认为这会使它变得更加复杂。这个怎么样:

import os

mypath = r'\path\to\folder'
for file in os.listdir(mypath): # This will loop through every file in the folder
    if '.csv' in file:  # Check if it's a csv file
        fpath = os.path.join(mypath, file)
        fpath_out = fpath + '_output' # Create an output file with a similar name to the input file
        with open(fpath) as infile
            lines = infile.readlines()  # Read all lines
        with open(fpath_out, 'w') as outfile:
            for line in lines:  # One line at a time
                outfile.write(line.replace('"', '')) # Remove each " and write the line

让我知道这是否有效,并回复您可能遇到的任何错误消息。

我根据 u/Jeff 提供的原始答案找到了解决方案。确切地说,它实际上是智能引号 (u'\u201d'),而不是直引号。这就是为什么我无法工作的原因。这是度过两天的好方法,现在如果你不介意的话,我得从屋顶上跳下去了。但是对于后代来说,这就是我使用过的方法。 (请注意 - 还有左弯智能引号 - 即 u'\u201c'。

mypath = 'C:\csv\'
myoutputpath = 'C:\csv\output\'

for file in os.listdir(mypath): # This will loop through every file in the folder
    if '.csv' in file:  # Check if it's a csv file
        fpath = os.path.join(mypath, file)
        fpath_out = os.path.join(myoutputpath, file) #+ '_output' # Create an output file with a similar name to the input file
        with open(fpath) as infile:
            lines = infile.readlines()  # Read all lines
        with open(fpath_out, 'w') as outfile:
            for line in lines:  # One line at a time
                outfile.write(line.replace(u'\u201d', ''))# Remove each " and write the line

        infile.close()
        outfile.close()