因此,我正在编写此程序,该程序使用open()创建读取文件。当我尝试运行该程序时,出现以下错误:ValueError:关闭文件上的I / O操作(第18行)。
在有关该主题的每个问题中,问题始终与缩进有关。IE试图对未在同一循环中打开的文件进行操作。我对python有点生疏,但缩进对我来说似乎还不错。
我希望有人可以快速浏览一下,让我知道缩进是否错误,或者是否有其他原因导致该错误?代码(注释错误):
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")
看起来像是一个缩进问题:您真的是这个意思,infile.close()
并且outfile.close()
属于for line in infile:
loop吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句