[英]Python, delimiter for csv ';'
It is a simple task to change two columns in.csv file.更改.csv 文件中的两列是一项简单的任务。 I use this code:
我使用这段代码:
inn = open('tk.csv', 'w')
import csv
with open('input_2.csv') as File:
reader = csv.reader(File, delimiter=';')
for row in reader:
a = row[0]
b = row[1]
a, b = b, a
print(a,b, file=inn)
And it gives me the mane and value in the same column, separated by a blank space.它给了我在同一列中的鬃毛和值,用空格分隔。 I know, that in answer there should be delimiter ";"
我知道,回答中应该有分隔符“;” as in the input.csv to separate the name and value on 2 different columns.
如在 input.csv 中将名称和值分隔在 2 个不同的列上。 What should I do?
我应该怎么办?
print("%s,%s"%(a, b), file=inn)
# delimiter is comma above you can change it to whatever you want.
If you want ;
如果你愿意
;
as a delimiter in your output, you should write one.作为 output 中的分隔符,您应该写一个。 The delimiter you use is only relevant for the input.
您使用的分隔符仅与输入相关。
You can你可以
print("%s;%s" % (a, b), file=inn)
for outputting the delimiter,print("%s;%s" % (a, b), file=inn)
输出分隔符,print()
to produce the correct delimiter ( print(a, b, sep=';', file=inn)
),print()
生成正确的分隔符( print(a, b, sep=';', file=inn)
),csv.writer()
, which is the recommended way.csv.writer()
,这是推荐的方式。 You should use csv.writer for writing to csv like that:您应该使用 csv.writer 像这样写入 csv :
import csv
with open('tk.csv', 'w') as output_file:
writer = csv.writer(output_file, delimiter=';')
with open('input_2.csv') as input_file:
reader = csv.reader(input_file, delimiter=';')
for row in reader:
a = row[0]
b = row[1]
a, b = b, a
writer.writerow([a, b])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.