0

我在 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
4

2 回答 2

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)
于 2013-03-04T06:22:20.473 回答
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)
于 2013-03-04T06:22:35.457 回答