t1=open(r‘F:\a.txt‘,encoding=‘utf-8‘,mode=‘r‘) #加 r 防止字符转义 open打开
content=t1.read() #read读取
print(content)
t1.close() #close关闭
open内置函数,open底层调用的是操作系统的接口
encoding:可以不写(一般情况都写)否则使用操作系统默认编码
close关闭文件
Traceback (most recent call last):
File "E:/xiaoxiannv/pyth.py", line 22, in <module>
t1=open(‘F:\123.txt‘,encoding=‘utf-8‘,mode=‘r‘)
FileNotFoundError: [Errno 2] No such file or directory: ‘F:S.txt‘
####报错原因,字符转义,文件找不见
解决方法:
t1=open(r‘F:\a.txt‘,encoding=‘utf-8‘,mode=‘r‘) #加 r 防止字符转义
t1=open(‘F:\\a.txt‘,encoding=‘utf-8‘,mode=‘r‘) #加 t1=open(‘F:/a.txt‘,encoding=‘utf-8‘,mode=‘r‘) #改成/
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 2: illegal multibyte sequence
#####报错原因,文件存储与文件打开时编码本运行不一致
解决方法:
加上编码方式: encoding=‘utf-8‘
原文:https://www.cnblogs.com/xiaoxiannvdbky/p/14844751.html