文件处理,写作,阅读 [英] File Handling, Writing, Reading
问题描述
我偶然发现了文件处理问题,
第二行无缘无故地为您提供了9的值,
第三行给出了一个错误io.UnsupportedOperation:不可读
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", "w+")
c.write("Hey there")
content = c.read()
c.close
print (content)
我该如何解决?
推荐答案
第二行无缘无故为9
Second Line gives you an value of 9 for no reason
write()
函数。该值是写入文件的字符数。
That is the return value from the write()
function in Python 3. The value is the number of characters written to the file.
第三行给出错误io.UnsupportedOperation:不可读
Third Line gives an Error io.UnsupportedOperation: not readable
不确定您在这里做了什么。在 write()
之后,文件指针位于文件的末尾。如果您确实使用 w +
打开了文件,则应该看不到错误,但是应该从文件中读取0个字符。如果您以 w
模式打开文件,则将得到 io.UnsupportedOperation
异常,因为未打开文件阅读。检查您在测试时使用的模式。
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.
尝试以下操作:
with open('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))
输出:
Wrote 9 characters to file
Read 0 characters from file
''
After seeking to start, read 9 characters from file
'Hey there'
这篇关于文件处理,写作,阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!