Python错误检测到不一致的意图

时间:2016-06-07 17:26:25

标签: python csv replace

我正在使用python脚本来替换选项卡分隔文本文件的特定列中的某些字符。

如果我运行脚本,我会收到错误:检测到不一致的意图。

import csv
# File names: to read in from and read out to
input_file = "test.txt"
output_file = input_file + "-SA_input.txt"

with open(input_file) as to_read:
with open(output_file, "wb") as tmp_file:
    reader = csv.reader(to_read, delimiter = "\t")
    writer = csv.writer(tmp_file)

    desired_column = [1]        # text column

    for row in reader:     # read one row at a time
        myColumn = row[desired_column]   # build the output row (process)
        myColumn.replace('0', ' ')
        myColumn.replace('1', ' ')
        myColumn.replace('2', ' ')
        myColumn.replace('3', ' ')
        myColumn.replace('4', ' ')
        myColumn.replace('5', ' ')
        myColumn.replace('6', ' ')
        myColumn.replace('7', ' ')
        myColumn.replace('8', ' ')
        myColumn.replace('9', ' ')

        writer.writerow(row) # write it

非常感谢帮助! :)

2 个答案:

答案 0 :(得分:2)

而不是

with open(input_file) as to_read:
with open(output_file, "wb") as tmp_file:

你需要使用

with open(input_file) as to_read:
    with open(output_file, "wb") as tmp_file:

答案 1 :(得分:0)

您有缩进错误,并且您有混合空格和制表符。始终使用制表符缩进。