Python - 打开读/写错误
我已经看过很多答案,但都没有解决我的问题。我需要一段代码,如果文件不存在,就创建一个文件,然后打开它进行读写。现在代码可以写入文件,但不能读取文件,这是什么原因呢?
>>> `file = open('test.txt', 'w+')`
>>> file.write('this is a test')
14
>>> file.read()
''
>>>
1 个回答
2
在尝试读取文件之前,你需要先把读取位置移动到文件的开头。
>>> _file = open('test.txt', 'w+')
>>> _file.write('this is a test')
14
>>> _file.read()
''
>>> _file.seek(0)
0
>>> _file.read()
'this is a test'
>>>
0表示文件的开始位置。你可以通过调用 _file.tell()
来获取当前的位置。
你也可以把 _file.tell
和 _file.seek(offset, fromwhat)
结合起来使用。
另外,使用内置的名称(比如 file)作为变量名是不太好的做法。