So I'm writing this program which creates reads files using the open(). When I try to run the program is gives me the error: ValueError: I/O operation on closed file (line 18).
In every question I've seen on this topic, the issue always has to do with indentation. IE trying to operate on a file that was not opened in the same loop. I'm a bit rusty with my python, but the indentation looks just fine to me.
I was hoping someone could give it a quick look-over and let me know if the indentation is wrong, or otherwise if something else might be causing the error? It would be very greatly appreciated.
The The code (error is commented):
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")