赞
踩
open(name,mode,encoding)
name:是要打开目标文件名的字符串,可以包含文件所在的具体路径
mode:设置打开文件的模式:只读 r 、写入 w 、追加 a
encoding:编码格式 UTF-8
- f=open("C:/test.txt","r",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- print(type(f))
- f=open("C:/test.txt","r",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- print(type(f))
-
- print(f"读取十个字节的结果{f.read(10)}")
不指定参数就全部读取
- f=open("C:/test.txt","r",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- print(type(f))
-
- print(f"读取十个字节的结果{f.read()}")
连用多次read,后面的read会接着上一次read的结束位置读取
- f=open("C:/test.txt","r",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- print(type(f))
- print(f"读取十个字节的结果{f.read(10)}")
- print(f"读取十个字节的结果{f.read()}")
读取全部行,封装到列表里面
- f=open("C:/test.txt","r",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- print(type(f))
- lines=f.readlines()
- print(f"lines类型是{type(lines)}")
- print(f"lines内容是{(lines)}")
一次读取一行
- f=open("C:/test.txt","r",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- print(type(f))
- for line in f:
- print(line)
不关闭的话,当程序一直运行,文件就会一直被占用
文件.close()
- f=open("C:/test.txt","r",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- print(type(f))
- f.close()
with open("C:/test.txt","r",encoding="UTF-8") as f:
- with open("C:/test.txt","r",encoding="UTF-8") as f:
- # 路径以及名字 操作 编码格式,默认都是这个
- print(type(f))
-
当冒号后边的语句执行完,程序就会自动close文件
1.先打开文件 f=open()
2.进行写入操作 (写入到内存)
f.write("jack111222")
3.写入之后要 (刷新到硬盘)
f.flush()
4.关闭文件 (包括了3)
f.close()
w模式,文件不存在,会创建新文件
会自己创建一个新的文件,后进行写出
- f=open("D:/test3.txt","w",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- f.write("jack111222")
- f.flush()
- f.close()
w模式,文件存在,会把原来的覆盖掉
- f=open("D:/test3.txt","w",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- f.write(" 111222")
- f.flush()
- f.close()
在文件原有内容不变的基础上追加
不改变原来的内容,文件不存在也不能创建新文件
-
- f=open("D:/test3.txt","a",encoding="UTF-8")
- # 路径以及名字 操作 编码格式,默认都是这个
- f.write(" 6666")
- f.flush()
- f.close()
-
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。