0

As shown below, the code's purpose is to read from a file and store the new names inside a list. The user is prompted to enter as many names as they like until they input 'end'.

def name(): with open("Names.txt") as f: data = f.readlines() while True: name = raw_input('Input: ').upper() data.append(name) if name == "END": data.remove("END") data.sort() print data for i in data: f.write("%s\n" % i) f.close() name() 

I am attempting to write the ordered list to a file like so:

for i in data: f.write("%s\n" % i) 

However, it results in the following error:

f.write("%s\n" % i) ValueError: I/O operation on closed file 

I would've expected the file to contain something a little like assuming :

Alex Ben Callum David ... 

1 Answer 1

2

Because the file is closed before you trying to write the data into the file.

def name(): with open("Names.txt") as f: data = f.readlines() # here file is closed while True: name = raw_input('Input: ').upper() data.append(name) if name == "END": data.remove("END") data.sort() print data with open("Names.txt", 'w') as f: for i in data: f.write("%s\n" % i) name() 

You need to open the file again when writing data.

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

1 Comment

Thanks ;-) Works great. You might just want to fix the indentation ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.