|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
试了提前输入英文正常,中文的话读取就乱码- '甯屾湜鎴戠粓灏嗘垚涓洪珮瀵屽竻\n'
- >>> f.read()
- ''
- >>> f.close()
- >>> f.read()
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: I/O operation on closed file.
- >>> f.read(10)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: I/O operation on closed file.
- >>> f
- <_io.TextIOWrapper name='F:\\测试文本.txt' mode='r' encoding='cp936'>
- >>> f.read()
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: I/O operation on closed file.
- >>> f.tell()
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: I/O operation on closed file.
- >>> f=open("F:\\测试文本.txt")
- >>> f.read(5)
- '甯屾湜鎴戠'
- >>> f.tell
- <built-in method tell of _io.TextIOWrapper object at 0x0000017094CA11E0>
- >>> f.tell()
- 10
- >>> f.seek(0,10)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: invalid whence (10, should be 0, 1 or 2)
- >>> f.seek(0,10)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: invalid whence (10, should be 0, 1 or 2)
- >>> f.seek(0,0)
- 0
- >>> f.read()
- '甯屾湜鎴戠粓灏嗘垚涓洪珮瀵屽竻\n'
- >>> list(f)
- []
- >>> f.seek(0,0)
- 0
- >>> list(f)
- ['甯屾湜鎴戠粓灏嗘垚涓洪珮瀵屽竻\n']
- >>> f.seek(0,0)
- 0
- >>> f.write("为啥乱码")
- File "<stdin>", line 1
- f.write("为啥乱码")
- IndentationError: unexpected indent
- >>> f.write("为啥乱码")
- File "<stdin>", line 1
- f.write("为啥乱码")
- IndentationError: unexpected indent
- >>> f.close
- <built-in method close of _io.TextIOWrapper object at 0x0000017094CA11E0>
- >>> f.close()
- >>> f=open("F:\\测试文档.txt","w")
- >>> f.write("为啥会乱码")
- 5
- >>> f.close()
- >>> f=open("F:\\测试文档.txt")
- >>> f.read()
- '为啥会乱码'
- >>> f.close()
- >>> f=open("F:\\测试文本.txt")
- >>> f.read()
- '甯屾湜鎴戠粓灏嗘垚涓洪珮瀵屽竻\n'
- >>> f
- <_io.TextIOWrapper name='F:\\测试文本.txt' mode='r' encoding='cp936'>
- >>> f.close()
- >>> f=open("F:\\测试文档.txt")
- >>> f
- <_io.TextIOWrapper name='F:\\测试文档.txt' mode='r' encoding='cp936'>
- >>> f.read()
- '为啥会乱码'
- >>> f=open("F:\\测试文本.txt")
- >>> f.read()
- 'asdasdasdasadas\n'
- >>> f.seek(0,0)
- 0
- >>> f.read()
- '浣犱粬鍚椾负鍟ユ槸涔辩爜'
- >>> f.close()
- >>> f=open("F:\\测试文本.txt")
- >>> f.read()
- '浣犱粬鍚椾负鍟ユ槸涔辩爜'
- >>>
复制代码
本帖最后由 xiaosi4081 于 2021-7-21 07:39 编辑
我查看了你的错误,分三种:
1.IndentationError: unexpected indent —— 缩进问题
需要把你的语句和 IDLE 的指示符写在一起,不要空格
2.ValueError: I/O operation on closed file. —— 你已经关闭了文件,但还要调用文件
这个问题就是你先调用了 f.close() 在调用了 f.read()
把文件打开步骤:
- f=open("F:\\测试文本.txt","r",encoding="utf-8")
复制代码
重写一遍就行了
3.乱码问题
把文件打开步骤重写,解码为 utf-8 类型
- f=open("F:\\测试文本.txt","r",encoding="utf-8")
复制代码
求最佳
|
|