读文件
前置:新建一个txt文件,写入hello word,命名为Python91
创建do_file.py 文件
open函数,打开txt文件,代码如下
file=open(“Python91.txt”)
调用read方法
res=file.read()
输出
print(res)
open函数
语法:
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
其中mode 有十二种模式 分别为
r w a r+ w+ a+ rb rb+ wb wb+ ab ab+
r:read w:write a:append
file=open("Python91.txt","r") res=file.read()#进行完一次读取操作后 光标就到文末 不管你设定的是读取几个字符 file.write("666") #定义为只读,此处不能进行写操作,会报错 print(res)
file 文件open之后默认是r 只读模式 如果你要写入内容则会报错:io.UnsupportedOperation: not writable
r+ 方式 可读可写 先写的话是从头开始覆盖写 读光标之后的内容
如果写入中文 要