我在csv文件中有一系列文本:
7858.35924983374[%2C]1703.69341358077[%2C]-3.075},7822.85045874375[%2C]1730.80294308742[%2C]-3.53962362760298}
是否有替换替换[%2C]的技巧?
with open('C:\IM\C3D\CommonLibraries\unewuoxhwt5k.wi2.conduit', "rb") as fin, open('C:\IM\C3D\CommonLibraries\unewuoxhwt5k.wi2.conduit', "wb") as fout:
reader = csv.reader(fin)
writer = csv.writer(fout)
for row in reader:
new_row = []
for item in row:
new_row.append(item.replace('[%2C]', ','))
print row, "->", new_row
writer.writerow(new_row)
现在我收到一个文件,但它是空的,我收到了这个错误消息:
Traceback (most recent call last):
File "<pyshell#6>", line 6, in <module>
for item in row:
NameError: name 'row' is not defined
答案 0 :(得分:2)
你可以做到
In [47]: s.replace('[%2C]', ',')
Out[47]: '7858.35924983374,1703.69341358077,-3.075},7822.85045874375,1730.80294308742,-3.53962362760298}'
试试这个......
for row in row_reader:
new_row = []
for item in row:
new_row.append(item.replace('[%2C]', ','))
print row, "->", new_row
row_writer.writerow(new_row)
答案 1 :(得分:2)
你想要string.replace。
val.replace('[%2C]', ',')
编辑:
既然我理解了你的问题,我会更具描述性。首先,您要将[%2C]
转换为逗号,以便csv模块正确解析它。
就像我说的那样,你需要清理数据。
in_file = 'C:\IM\C3D\CommonLibraries\unewuoxhwt5k.wi2.conduit'
out_file = 'C:\IM\C3D\CommonLibraries\u2newuoxhwt5k.wi2.conduit.csv'
csv_outfile = 'C:\IM\C3D\CommonLibraries\u2newuoxhwt5k.wi2.conduit.csv.out'
with open(out_file, w) as outfile:
with open(in_file) as infile:
for line in infile:
outfile.write(line.replace('[%2C]', ','))
现在您可以进行CSV解析:
reader = csv.reader(out_file)
writer = csv.writer(csv_outfile)
for row in reader:
# do some processing on the row, which is a list of separated items
new_row = row + ["another item"]
writer.writerow(new_row)