0

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? 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") 
2
  • youre referencing the opened file, you never did a .read() to get the contents, youre also trying to close the file multiple times in the loop. Commented Jun 18, 2014 at 21:00
  • @MikeRixWolfe for line in infile already reads the file. Commented Jun 18, 2014 at 21:09

1 Answer 1

4

It looks like an indentation problem: do you really mean that infile.close() and outfile.close() belong to for line in infile: loop?

Sign up to request clarification or add additional context in comments.

2 Comments

You are correct! I knew the answer was right in front of my face. Thank you for the second set of eyes :)
@user2779949 I usually add a blank line after a block to make it more visually indented, that would help to see that infile.close() is at the wrong block.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.