r:只读 read
w: 只写 write
a : 追加写 append
#相对路径:相对于当前程序所在的文件夹
#绝对路径: c:/work/123.txt
文件操作回顾
# 1,ascii 8bit 1byte
2,gbk 16bit 2byte
3,Unicode 万国码 32bit 4byte
4,utf-8
英文:8bit, 1byte
欧洲:16bit,2byte
中文: 24bit,3byte
文件操作:
open(文件路径,mode="模式",encoding="utf-8")
mode:
r 读
w 写
a 追加
+ 扩展
b 字节操作 非文本文件
read() #读文件
readline()读一行
for line in f:
print (line)
write(1.txt)#写文件
with open (1.txt) as f:
XXXX
f.close()#关闭打开的文件
# 读取文件
f = open ("D:/py/文件读取/123.txt",mode = "r" ,encoding="utf-8")
print (f.read())#全部读取
# w 写入文件
# w 模式下可以帮我们创建文件
# w写入的一瞬间,会清空源文件内容写入新内容
f = open ("D:/py/文件读取/1234.txt",mode = "w" ,encoding="utf-8")
f.write("笑傲江湖")
f.write("令狐冲
")
f.write("东方不败
")
f.write("任盈盈
")
f.write("任我行
")
f.write("岳灵珊
")
f.write("林平之
")
# a 写入文件
# f = open ("D:/py/文件读取/12345.txt",mode = "a" ,encoding="utf-8")
# f.write("令狐冲
")
# f.write("东方不败
")
# f.write("任盈盈
")
# f.write("任我行
")
# f.write("岳灵珊
")
# f.write("林平之
")
# mode : r+ 读写操作
# w+ 写读
# a+ 追加写读
# mode : b 字节bytes 不需要给出编码,读写非文本文件(图片,音乐,视频等)
# 文件复制
# f1 = open("D:/py/文件读取/雨.jpg",mode="rb")
# f2 = open("D:/py/文件读取/1/雨.jpg",mode="wb")
# for line in f1:
# f2.write(line)
# f1.close() # 关闭文件连接
# f2.close()
# with open("D:/py/文件读取/123456.txt",mode="w","utf-8") as f: # 打开文件完成后自动关闭
# f.write("AAAAAAAAAAAA")
# 文件修改
# 创建一个文件副本
# 从源文件中读取内容,加载到内存,然后在内存进行修改,写入到文件副本
# 然后删除源文件
# 把副本文件重名成原文件名字
# with open("D:/py/文件读取/颜色_副本",mode="w",encoding="utf-8") as f1,
# open ("D:/py/文件读取/颜色",mode="r",encoding="utf-8") as f2:
# for line in f2:#从源文件中读取内容
# line = line.replace("黑","嘿嘿嘿嘿嘿嘿额嘿嘿嘿嘿hi欸")
# f1.write(line)# 写入到新文件
# os.remove("颜色")
# os.rename("颜色_副本","人名单")
# 文件操作读取固定格式的数据
# f = open("D:/py/文件读取/水果",mode = "r",encoding= " utf-8")
# lit = [] #最终承载数据的地方
# for line in f:
# line = line.strip() #"1,苹果,9.9,10000"
# line_lst = line.split(",") #[1,苹果,9.9,10000]
# num = line_lst[0]
# name = line_lst[1]
# price = line_lst[2]
# count = line_lst[3]
# dic = {"编号":num,"名称":name,"价格":price,"库存":count}
# lit.append(dic)
# print (lit)
#w = open("D:/py/文件读取/url2.txt",mode="w",encoding="utf-8")
# f = open("D:/py/文件读取/url1.txt",mode = "r",encoding= " utf-8")
#
# for line in f:
# line = line.strip(" ")
# line_lst = line.split()
# for gpc in line_lst[0].split(" "):
# None
# for gpc1 in line_lst[1].split():
# None
# for gpc2 in line_lst[2].split("、"):
# None
#
# print (gpc + " " + gpc1 + " " + gpc2 )
with open('filename') as f: #把操作的结果, 赋给as后面的对象
print(f.read())