所以我正在编写这个程序,它使用open()创建读取文件。当我尝试运行程序时给出了错误:ValueError:关闭文件的I / O操作(第18行)。
在我在这个主题上看到的每个问题中,问题总是与缩进有关。 IE尝试操作未在同一循环中打开的文件。我的蟒蛇有点生疏,但缩进对我来说很好看。
我希望有人可以快速查看,让我知道缩进是否错误,或者是否有其他可能导致错误? 代码(错误被评论):
sourceFile = 'test.html'
serviceTarget = "Plumbers & HVAC Experts"
cityTarget = "NJ"
services = {"Plumbers", "Air Conditioning Experts", "Drain Cleaning Experts"}
cities = {"Westfield", "Scotch Plains", "Clark"}
serviceNames = {"Plumbers":"plumbers", "Air Conditioning Experts":"ac", "Drain Cleaning Experts":"drain"}
totalPages = len(services)*len(cities)
for serviceRep in services:
for cityRep in cities:
outFileName = cityRep + " " + serviceNames[serviceRep] + ".html"
outFileName = outFileName.replace(" ", "_");
print("Writing " + outFileName + "...")
infile = open(sourceFile)
outfile = open(outFileName, 'w')
for line in infile: #This is the line giving me problems
if serviceTarget in line:
line = line.replace(serviceTarget,serviceRep)
if cityTarget in line:
line = line.replace(cityTarget,cityRep)
outfile.write(line)
infile.close()
outfile.close()
totalPages -= 1;
print("DONE -- " + str(totalPages) + " left to go")
答案 0 :(得分:5)
这看起来像是缩进问题:您是否真的是指infile.close()
和outfile.close()
属于for line in infile:
循环?