Enigmatic
Enigmatic

Reputation: 4158

Error when attempting to write to file on new line

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
...

Upvotes: 0

Views: 52

Answers (1)

Ke Li
Ke Li

Reputation: 952

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.

Upvotes: 2

Related Questions