Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x python:如何允许python在更改csv文件中的分隔符时不添加引号_Python 3.x_Csv_Delimiter_Quotation Marks - Fatal编程技术网

Python 3.x python:如何允许python在更改csv文件中的分隔符时不添加引号

Python 3.x python:如何允许python在更改csv文件中的分隔符时不添加引号,python-3.x,csv,delimiter,quotation-marks,Python 3.x,Csv,Delimiter,Quotation Marks,我编写了一个脚本,将csv文件中的分隔符从逗号转换为管道符号,但在执行此操作时,它不会删除csv文件添加的额外引号 脚本如下:- import csv filename = "sample.csv" with open(filename,mode='rU') as fin,open('c:\\files\\sample.txt',mode='w') as fout: reader= csv.DictReader(fin) writer = csv.DictW

我编写了一个脚本,将csv文件中的分隔符从逗号转换为管道符号,但在执行此操作时,它不会删除csv文件添加的额外引号

脚本如下:-

import csv

filename = "sample.csv"

with open(filename,mode='rU') as fin,open('c:\\files\\sample.txt',mode='w') as fout:

        reader= csv.DictReader(fin)
        writer = csv.DictWriter(fout,reader.fieldnames,delimiter='|')
        writer.writeheader()
        writer.writerows(reader)
案例1: 现在,例如,如果csv中的一个字段包含“hi”hows you,good,那么csv将使其成为““hi”hows you,good”,python将其加载为文本文件中的““hi”hows you,good”,而不是“hi”hows you,good”

案例2: 而对于像hi hows这样的字段,csv将其设置为“hi hows,you”,并且在运行脚本后,它将保存为hi hows,you,保存在文本文件中,这是正确的

你能帮我解决第一个案子吗

在记事本中打开csv文件的示例:-

ID,IDN,DESC,TNO
A019,1,"""Pins ""  is dangerous",2
B020,1,"""ache"",headache/fever-like",3
C021,2,stomach cancer,1
D231,3,"hair,""fall""",1
脚本结果之后:

ID|IDN|DESC|TNO
A019|1|"""Pins ""  is dangerous"|2
B020|1|"""ache"",headache/fever-like"|3
C021|2|stomach cancer|1
D231|3|"hair,""fall"""|1
我希望结果如下:

ID|IDN|DESC|TNO
A019|1|"Pins "  is dangerous|2
B020|1|"ache",headache/fever-like|3
C021|2|stomach cancer|1
D231|3|hair,"fall"|1
这是有效的:

writer = csv.DictWriter(fout,reader.fieldnames,delimiter='|',quoting=csv.QUOTE_NONE,quotechar="")
  • 将报价定义为“无报价”:
    quoting=csv.QUOTE\u NONE
  • 将引号字符定义为“无引号字符”:
    quotechar=”“
结果

ID|IDN|DESC|TNO
A019|1|"Pins "  is dangerous|2
B020|1|"ache",headache/fever-like|3
C021|2|stomach cancer|1
D231|3|hair,"fall"|1

请注意,引用是有用的。因此,禁用它会让您感受到“字段中的分隔符”的乐趣。由您来确保不会发生这种情况。

您可以发布
sample.csv
输入文件吗?请注意,如果您在csv数据中实际使用管道(或换行符),这将导致无法正确往返。答案中已添加。实际上,我认为OP想要创建一个简单的文件,
cut
awk
可以毫无问题地解析。