
Py 文件操作
一:


"""1.找到这个文件,双击打开
open(文件路径,mode="",encoding="")mode=>读/写encoding=>文件的编码集是什么
文件路径: 1.绝对路径 d:Tools/Tool/python/a.txt 不安全 2.相对路径 相对于当前你的程序所在的文件夹
../ 上一层文件夹 mode: r:read 读取"""open("日常.txt")open("../穿搭.txt")open("../demo03_xpath/素材/豆瓣.html")
f = open("日常.txt",mode='r',encoding="utf-8")
content = f.read()
二.
line = f.readline()print(line)
line = f.readline()print(line)

这里换行是因为 print 本身自带换行,而文件内容里还有一个换行 可以使用 strip()函数,去掉字符串左右两端的空白。空格,换行,制表符
line = f.readline().strip()
print(line)
line = f.readline().strip()
print(line)
content = f.readlines()
print(content)
['大丈夫生与天地之间,\n', '岂能郁郁久居人之下.']
for line in f:
print(line.strip())
三:
"""
mode:
r:read 读取
w:write 写
"""
f = open("sport.txt",mode="w",encoding="utf-8")
f.write("足球")
f.write("网球")
f.close()
lst = ['小a','小b','小c','小d']
f = open("选美.txt",mode="w",encoding="utf-8")
f.write(lst[0])
f.write("\n")
f.write(lst[1])
f.write("\n")
f.write(lst[2])
f.write("\n")
f.write(lst[3])
f.write("\n")
f.close()
"""
mode:
r:read 读取
w:write 写
a:append 追加写入
"""
f = open("选美/txt",mode="a",encoding="utf-8")
f.write("你们好美丽")
四:
"""
mode:
r:read 读取
w:write 写
a:append 追加写入
b:读写的是非文本文件 ->bytes
with: 上下文,不需要手动去关闭一个文件
#with
with open("日常.txt",mode="r",encoding="utf-8")as f: #f=open()
for line in f:
print(line.strip())
#想要读取图片
#在读写
with open("小黄.jpeg",mode="rb") as f:
for line in f:
print(line)
#文件的复制:
#从源文件中读取内容,写入到新路径去
with open("小黄.jpeg",mode="rb") as f1,\
open("../demo00_re/小黄.jepg",mode="wb")as f2:
for line in f1:
f2.write(line)

import os
with open("人名单.txt",mode="r",encoding="utf-8") as f1,\
open("人名单_副本.txt",mode="w",encoding="utf-8") as f2:
for line in f1:
line = line.strip()
if line.startswith("周"):
line=line.replace("周","Lee")
f2.write(line)
f2.write("\n")
os.remove("人名单.txt")
os.rename("人名单_副本.txt","人名单.txt")