[英]How to specify “,” as 3-character delimiter string in .csv?
How to specify (when reading a file) and assign (in output) this 3-character string ","
as .csv
delimiter? 如何指定(读取文件时)并将此3个字符的字符串
","
分配为.csv
分隔符(在输出中)? For example: "col1","col2","col3","col4"
例如:
"col1","col2","col3","col4"
The code where it needs to be used for reading and output: 需要用于读取和输出的代码:
import csv
with open('a.csv', 'r') as infile, open('reordered.csv', 'a') as outfile:
fieldnames = ['B', 'C', 'A', 'D']
writer = csv.DictWriter(outfile, delimiter=',', fieldnames=fieldnames)
writer.writeheader()
for row in csv.DictReader(infile):
writer.writerow(row)
I tried to look it up ( https://docs.python.org/2.0/ref/strings.html ), etc. but it is not clear. 我试图查找它( https://docs.python.org/2.0/ref/strings.html ),等等,但不清楚。
UPDATE: As pointed out by others, this may not be ","
delimiter, but a ,
delimiter and "values"
. 更新:正如其他人所指出的,这可能不是
","
分隔符,而是a ,
分隔符和"values"
。 Regardless, my values contain commas ,
, so the ","
pattern between columns helps to maintain column structure. 无论如何,我的价值观包含逗号
,
,所以","
列之间的模式有助于保持柱结构。
You'll want to define the quote character , setting the delimiter will not get you the desired results. 您将需要定义引号字符 ,设置定界符将无法获得所需的结果。
import csv
with open('a.csv', 'r') as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
for row in reader:
print row
Edit: As for changes to your code, it would look somewhat like this: 编辑:至于对您的代码的更改,它将看起来像这样:
with open('a.csv', 'r') as infile, open('reordered.csv', 'a') as outfile:
fieldnamesout = ['B', 'C', 'A', 'D']
fieldnamesin = ['A', 'B', 'C', 'D']
reader = csv.DictReader(infile, delimiter=',', quotechar='"', fieldnames=fieldnamesin)
writer = csv.DictWriter(outfile, delimiter=',', quotechar='"', fieldnames=fieldnamesout, quoting=csv.QUOTE_ALL)
for row in reader:
writer.writerow(row)
Note the quoting=csv.QUOTE_ALL
, which instructs the writer to quote all fields according to the quotechar
, this may or may not be what you want, other options would be quoting=csv.QUOTE_NONNUMERIC
. 请注意
quoting=csv.QUOTE_ALL
,它指示编写者根据quotechar
引用所有字段,这可能是您想要的,也可能不是您想要的,其他选项将是quoting=csv.QUOTE_NONNUMERIC
。
Seems like your values are string literals. 好像您的值是字符串文字。 I don't know if the cvs module can handle this out of the box.
我不知道cvs模块是否可以开箱即用。 It is not a parsing problem it is a data processing problem.
这不是解析问题,而是数据处理问题。
Your values are in the quote chars. 您的值在报价字符中。 So either you truncate them when processing your data
field_value.replace('"', '')
and add them back later on '"{}"'.format(field_value)
or you straight operate on the data fields leaving the quote char in place. 因此,您可以在处理数据
field_value.replace('"', '')
时截断它们,然后稍后再将它们添加到'"{}"'.format(field_value)
或者直接对数据字段进行操作,而将引号char保留在地点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.