AllTheTime1111
AllTheTime1111

Reputation: 111

Writes, Deletes, but won't read text file

I just started learning python today. This is a simple script to either read, write one line to, or delete a text file. It writes and deletes just fine, but when choosing the 'r' (read) option i just get the error:

IOError: [Errno 9] Bad file descriptor

What am I missing here...?

from sys import argv

script, filename = argv

target = open(filename, 'w')

option = raw_input('What to do? (r/d/w)')

if option == 'r':   
    print(target.read())

if option == 'd':
    target.truncate()
    target.close()  

if option == 'w':
    print('Input new content')
    content = raw_input('>')
    target.write(content)
    target.close()  

Upvotes: 2

Views: 164

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

You've opened the file in write mode, so you can't perform read on it. And secondly 'w' automatically truncates the file, so your truncate operation is useless. You can use r+ mode here:

target = open(filename, 'r+')

'r+' opens the file for both reading and writing

Use the with statement while opening the file, it automatically closes the file for you:

option = raw_input('What to do? (r/d/w)')

with  open(filename, "r+")  as target:
    if option == 'r':
        print(target.read())

    elif option == 'd':
        target.truncate()

    elif option == 'w':
        print('Input new content')
        content = raw_input('>')
        target.write(content)

As @abarnert has suggested it'll be better to open the file as per the mode entered by user, because read only files may raise error with 'r+' mode in first place:

option = raw_input('What to do? (r/d/w)')

if option == 'r':
    with open(filename,option) as target:
        print(target.read())

elif option == 'd':
    #for read only files use Exception handling to catch the errors
    with open(filename,'w') as target:
        pass

elif option == 'w':
    #for read only files use Exception handling to catch the errors
    print('Input new content')
    content = raw_input('>')
    with open(filename,option) as target:
        target.write(content)

Upvotes: 9

Related Questions