您好我是python的新手,我想编写一个程序来读取csv文件并将数据写入另一个文件。
以下是代码:
#!/usr/bin/python
import csv
FEED_FILE = '/proj/ctc/temp/sanjay/REC-754/20170529_MUREX_EOD_REC_RATES_20170531.csv'
OUT_FILE = '/proj/ctc/temp/sanjay/REC-754/20170529_MUREX_EOD_REC_RATES_20170531_out.csv'
with open(OUT_FILE, 'w', newline='') as outputfile:
with open(FEED_FILE, newline='') as feed:
writer = csv.writer(outputfile, delimiter=',', quotechar='"')
reader = csv.reader(feed, delimiter=',', quotechar='"')
for row in reader:
row[3] = sorted(list(row[3].split(','))
writer.writerow(row)
但是我得到了以下错误,我无法理解为什么?
$./Csvreader.py
File "./Csvreader.py", line 14
writer.writerow(row)
^
SyntaxError: invalid syntax
请提前帮助我解决问题。
答案 0 :(得分:0)
问题在于缩进!
with open(OUT_FILE, 'w', newline='') as outputfile:
with open(FEED_FILE, newline='') as feed:
writer = csv.writer(outputfile, delimiter=',', quotechar='"')
reader = csv.reader(feed, delimiter=',', quotechar='"')
for row in reader:
row[3] = sorted(list(row[3].split(','))
writer.writerow(row)
编辑: 对于您更新的问题,再次出现缩进问题!
此
row[3] = sorted(list(row[3].split(','))
writer.writerow(row)
应该是
row[3] = sorted(list(row[3].split(','))
writer.writerow(row)
答案 1 :(得分:0)
请尝试以下代码:
with open(OUT_FILE, 'w', newline='') as outputfile:
with open(FEED_FILE, newline='') as feed:
writer = csv.writer(outputfile, delimiter=',', quotechar='"')
reader = csv.reader(feed, delimiter=',', quotechar='"')
for row in reader:
row[3] = sorted(list(row[3].split(',')))
writer.writerow(row)