python - Writes, Deletes, but won't read text file -
i started learning python today. simple script either read, write 1 line to, or delete text file. writes , deletes fine, when choosing 'r' (read) option error:
ioerror: [errno 9] bad file descriptor
what missing here...?
from sys import argv script, filename = argv target = open(filename, 'w') option = raw_input('what 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()
you've opened file in write mode, can't perform read on it. , secondly 'w'
automatically truncates file, truncate operation useless. can use r+
mode here:
target = open(filename, 'r+')
'r+' opens file both reading , writing
use with
statement while opening file, automatically closes file you:
option = raw_input('what do? (r/d/w)') open(filename, "r+") 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 better open file per mode entered user, because read files may raise error 'r+'
mode in first place:
option = raw_input('what do? (r/d/w)') if option == 'r': open(filename,option) target: print(target.read()) elif option == 'd': #for read files use exception handling catch errors open(filename,'w') target: pass elif option == 'w': #for read files use exception handling catch errors print('input new content') content = raw_input('>') open(filename,option) target: target.write(content)
Comments
Post a Comment