文件操作

1. 文件操作

  • open() -- 打开
  • file -- 文件的位置(路径)
  • mode -- 操作文件的模式
  • encoding -- 文件编码模式
  • f -- 文件句柄

2. 文件操作的模式

2.1 r,w,a (重要)

2.1.1 r 操作

f = open("文件名称",mode="r",encoding="utf-8")
print(f.read())   #全部读取
f = open("文件名称",mode="r",encoding="utf-8")
print(f.read(3))  #按照字符进行读取
f = open("文件名称",mode="r",encoding="utf-8")
print(f.readline())    #按行读取,两行之间自动添加换行 运行格式:

print(f.readline())
f = open("文件名称",mode="r",encoding="utf-8")
print(f.readline().strip())  #按行读取,脱掉换行符
f = open("文件名称",mode="r",encoding="utf-8")
print(f.readlines())  #一行一行读取,存放在列表中
结果:
['大黑哥你真牛
', '18732195032
', '18019086306
', '13716165697
']

2.1.2 解决大文件

f = open("文件名称",mode="r",encoding="utf-8")
for i in f:
	print(i)  # 一行一行读取

2.2.1 w 操作

  • 先清空文件
  • 写入文件
f = open("文件名称",mode="w",encoding="utf-8") ## mode可以不写
print(f.write("123456"))  
f = open("文件名称",mode="w",encoding="utf-8") ## mode可以不写
print(f.write("123456"))  
print(f.write("123456"))
print(f.write("123456")) 
结果:
123456123456123456  #连在一起写了3遍,只有运行open时会清空
f = open("文件名称","w",encoding="utf-8") ## mode可以不写
print(f.write("123456
"))
print(f.write("123456
"))
print(f.write("123456
"))  #添加换行符
结果:
123456
123456
123456

2.3 路径

  • 绝对路径--C:usermeetpython文件名称 获取:右键--copy path
f = open("E:PyCharmday08文件名称","r",encoding="utf-8")
print(f.read())
结果:
123456
123456
123456
  • 相对路径(推荐使用)
f = open("文件名称",mode="r",encoding="utf-8")
print(f.read())   ##文件名称就是相对路径  ##如果移动到别的文件夹里就不行了
  • .. 点点杠 返回上一层
f = open("..day07文件名称",mode="r",encoding="utf-8") 
print(f.read()) 

2.4 a 操作 追加

f = open("..day07文件名称","a",encoding="utf-8") 
print(f.read()) 

2.2 rb,wb,ab

2.3 r+, w+ , a+

原文地址:https://www.cnblogs.com/lvweihe/p/11275939.html