File Handling, Writing, Reading
I stumbled across an issue of file handling, second line gives you an value of 9 for no reason, third line gives an Error io.UnsupportedOperation: not readable c = open('Test.txt'
Solution 1:
Second Line gives you an value of 9 for no reason
That is the return value from the write()
function in Python 3. The value is the number of characters written to the file.
Third Line gives an Error io.UnsupportedOperation: not readable
Not sure what you've done here. Following the write()
, the file pointer is positioned at the end of the file. If you really opened the file with w+
then you should not see an error, but 0 characters should be read from the file. If you opened the file with mode w
, then you would get the io.UnsupportedOperation
exception because the file is not opened for reading. Check which mode you used when you tested.
Try this:
withopen('Test.txt', 'w+') as c:
n = c.write("Hey there")
print('Wrote {} characters to file'.format(n))
content = c.read()
print('Read {} characters from file'.format(len(content)))
print('{!r}'.format(content))
_ = c.seek(0) # move file pointer back to the start of the file
content = c.read()
print('After seeking to start, read {} characters from file'.format(len(content)))
print('{!r}'.format(content))
Output:
Wrote 9 characters to file Read 0 characters from file '' After seeking to start, read 9 characters from file 'Hey there'
Post a Comment for "File Handling, Writing, Reading"