python - 用字符串周围的引号编写 csv (Python)

标签 python csv parsing text quotes

我编写了以下代码来获取一个大型 csv 文件,并根据列中的特定单词将其拆分为多个 csv 文件。原始 csv 文件有一些是字符串的字段,它们周围有引号。
例如:

Field1,Field2,Field3,Field4
1,2,"red",3
1,4,"red",4
3,4,"blue",4
等等。
我的代码基于 Field4 将文件拆分为单独的 csv。
我的输出如下所示:
3.csv
Field1,Field2,Field3,Field4
1,2,red,3

4.csv
Field1,Field2,Field3,Field4
1,4,red,4
3,4,blue,4
我希望我的输出保留字段 3 中字符串周围的引号。这些文件被输入到一个软件中,该软件仅在字符串周围有引号时才有效,这很烦人。
我当前的代码如下所示:
import csv

#Creates empty set - this will be used to store the values that have already been used
newfilelist = set()

#Opens the large csv file in "read" mode
with open('File.csv', 'r') as csvfile:
    
    #Read the first row of the large file and store the whole row as a string (headerstring)
    read_rows = csv.reader(csvfile)
    headerrow = next(read_rows)
    headerstring=','.join(headerrow) 
    for row in read_rows:
        
        #Store the whole row as a string (rowstring)
        rowstring=','.join(row)
        
        #Takes Field 4
        newfilename = (row[3])
        
        
        #This basically makes sure it is not looking at the header row.
        if newfilename != "field4":
        
            
            #If the newfilename is not in the newfilename set, add it to the list and create new csv file with header row.
            if newfilename not in newfilelist:    
                newfilelist.add(newfilename)
                with open('//output/' +str(newfilename)+'.csv','a') as f:
                    f.write(headerstring)
                    f.write("\n")
                    f.close()    
            #If the newfilename is in the newfilelist set, append the current row to the existing csv file.     
            else:
                with open('//output/' +str(newfilename)+'.csv','a') as f:
                    f.write(rowstring)
                    f.write("\n")
                    f.close()
 
任何人都可以告诉我如何获得字符串周围的引号?不幸的是,使用我的文件的软件要求它们采用这种格式!

最佳答案

通行证quoting=csv.QUOTE_NONNUMERICcsv.writer() .

关于python - 用字符串周围的引号编写 csv (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47187792/

相关文章:

c# - 从 .NET Core Controller 返回 CSV

r - 如何在 R 中读取一行一行的 CSV?

c# - 如何在 Irony.NET 中允许重复

android - 解析 SharedPreferences 字符串

python - 如何将字符串解析为 float 或整数?

python - Pandas Dataframe 中的第二天或下一行索引

python - 为什么 split is_text_present() 会导致 Firefox 间歇性出现 StaleElementReferenceException(但 Chrome 或 phantomjs 不会)?

Python不返回目录值

c - 如何将 CSV 文件读入结构的二维数组,其中每个元素都有一个确定字符(C、G、M)来排序到结构中?

python - 间歇性 "getrandom() initialization failed"使用 scrapy spider