我尝试使用如下输出写入CSV文件:
14897,40.50891,-81.03926,168.19999
但CSV编写器一直在开头和结尾用引号写输出
' 14897,40.50891,-81.03926,168.19999'
当我正常打印线时,输出是正确的但我需要执行line.split(),否则csv writer将输出设为1,4,8,9,7等...
但是当我执行line.split()时,输出就是
[' 14897,40.50891,-81.03926,168.19999']
编写为' 14897,40.50891,-81.03926,168.19999'
如何让报价消失?我已经尝试过csv.QUOTE_NONE但是没有工作。
with open(results_csv, 'wb') as out_file:
writer = csv.writer(out_file, delimiter=',')
writer.writerow(["time", "lat", "lon", "alt"])
for f in file_directory):
for line in open(f):
print line
line = line.split()
writer.writerow(line)
答案 0 :(得分:1)
使用line.split()
,您不是按照逗号分隔,而是分为空格(空格,换行符,制表符)。由于没有,最终每行只有1个项目。
由于此项目包含逗号,csv
模块必须引用以与实际分隔符(也是逗号)区分开来。您需要line.strip().split(",")
才能使用它,但是......
使用csv
读取您的数据会更好地解决这个问题:
替换:
for line in open(some_file):
print line
line = line.split()
writer.writerow(line)
由:
with open(some_file) as f:
cr = csv.reader(f) # default separator is comma already
writer.writerows(cr)
答案 1 :(得分:0)
您无需手动阅读该文件。你可以简单地使用csv阅读器。 用以下内容替换内部for循环:
# with ensures that the file handle is closed, after the execution of the code inside the block
with open(some_file) as file:
row = csv.reader(file) # read rows
writer.writerows(row) # write multiple rows at once