谁想帮助新手?我一直收到缩进错误,或者当我管理正确的缩进时,由于文件已经被打开方式自动关闭,所以我最终遇到了IO错误。我在做什么错了?
这是我的脚本;
import csv
infile = ('Test')
with open(infile+'.txt') as csvfile, open('output.csv', 'w', encoding='utf-8') as outfile:
lines = sorted(set(line.strip('\n').lower() for line in csvfile))
for line in lines:
writer = csv.writer(outfile, lineterminator='\n', quoting=csv.QUOTE_ALL)
writer.writerow(line)
感谢您的帮助!
答案 0 :(得分:0)
缩进代码以在with语句下写出。 您那里还有一些空格,这些空格已排除掉缩进。我拼合了您的代码,然后缩进了代码。您可能必须先以读写方式打开,或者先打开一次才能读取,然后再打开一次即可。
import csv
infile = ('Test')
with open(infile+'.txt') as csvfile, open('output.csv', 'w', encoding='utf-8') as outfile:
lines = sorted(set(line.strip('\n').lower() for line in csvfile))
for line in lines:
writer = csv.writer(outfile, lineterminator='\n', quoting=csv.QUOTE_ALL)
writer.writerow(line)
答案 1 :(得分:0)
我编辑了原始问题的格式。如果我的编辑没有以某种方式弄乱事情,则可能的问题是,通过在同一infile
块中同时打开和关闭outfile
和with
,您已经在以下情况下关闭了outfile
您要写它。
如果您这样重新排列它,则可能会更容易预测
import csv
infile = ('Test')
with open(infile+'.txt') as csvfile:
lines = sorted(set(line.strip('\n').lower() for line in csvfile))
with open('output.csv', 'w', encoding='utf-8') as outfile:
writer = csv.writer(outfile, lineterminator='\n', quoting=csv.QUOTE_ALL)
for line in lines:
writer.writerow(line)