参数1:文件的路径
参数2 mode:
r 读取,不存在FileNotFoundError
a+ 在文件最后添加内容,不存在会创建文件
w 覆盖内容文件内容,不存在会创建文件
x 创建文件,如果文件存在返回错误
参数3:编码格式
# 文件读取
# r 读取,不存在报错 FileNotFoundError: [Errno 2] No such file or directory: '1.txt'
# a+ 在文件最后添加内容,不存在会创建文件
# w 覆盖内容文件内容,不存在会创建文件
file = open(r"1.txt", "a+", encoding="utf-8")
file.seek(0) # 将光标移到开始位置
print(file.read()) # 读取所有内容
print("~~~~~~~~~~~~~~~~~~~")
file.seek(0) # 将光标移到开始位置
print(file.read(8)) # 读取前8个字符
print("~~~~~~~~~~~~~~~~~~~")
file.seek(0) # 将光标移到开始位置
print(file.readline()) # 读取整行内容,自带换行符
print(file.readline())
print(file.readline())
print("~~~~~~~~~~~~~~~~~~~")
file.seek(0) # 将光标移到开始位置
for f in file: # 遍历文件每一行的内容
print(f)
file.close() # 关闭流
# a+ 在文件末尾添加新内容,不存在会创建文件
# w 覆盖内容文件内容,不存在会创建文件
file = open(r"2.txt", "a+", encoding="utf-8")
file.write("新内容 rn") # 写入新内容
file.seek(0)
print(file.read())
file.close()
2. 常用的方法
import os
if os.path.exists(r"2.txt"):
os.remove(r"2.txt") # 不进回收站,删除大文件效率高
print("删除完成")
else:
print("文件不存在")
os.remove(r"2.txt") # FileNotFoundError: [WinError 2] 系统找不到指定的文件。: '2.txt'
os.rmdir("aaa") # 删除空文件夹,如果不为空 OSError: [WinError 145] 目录不是空的。: 'aaa'
# 如果不存在FileNotFoundError: [WinError 2] 系统找不到指定的文件。:
# 获取当前运行目录
print(os.getcwd())
print(os.getcwd() + "\1,txt")
files = os.listdir("c:\") ## 读取所有文件和文件夹,包括隐藏
for f in files:
print(f)
# 创建文件
os.mkdir(r"D:testtesttest") # 只能创建单层目录,创建多层会出错FileNotFoundError
os.makedirs(r"D:testtesttest") # 创建多层文件夹
3.补充知识Time
import time
while True:
print(time.strftime("%Y年%m月%d日 %H:%M:%S", time.localtime()))
time.sleep(1) # 每一分钟执行一次
def getTime():
return time.strftime("%Y%m%d%H%M%S", time.localtime())
4.二进制文件拷贝
import os
of = open(r"d:t1.jpeg", "rb")
nf = open(os.getcwd()+"\备份\"+getTime()+".jpeg", "wb")
nf.write(of.read())
of.close()
nf.close()
print("完成")
with open(r"d:t1.jpeg", "rb") as file: # 可以自动捕获异常和关闭流
rf = file.read()
with open(r"d:备份t1.jpeg", "wb") as wf: # rb nb都是以二进制文件来读取
wf.write(rf)
5.备份文件
import os
import time
class Common:
# 获取当前时间的年月日时分秒:20220601123710
@staticmethod
def getNowTime():
return time.strftime("%Y%m%d%H%M%S", time.localtime())
oldFilePath = input("请输入需要备份的文件绝对路径:")
oldFile = open(oldFilePath, "a+", encoding="utf-8")
# 新文件路径获取 当前运行目录+备份+当前年月日时分秒+旧文件的后缀
newFilePath = os.getcwd()+"\备份\" + Common.getNowTime() + oldFilePath[oldFilePath.rfind("."):]
# 打开新文件
newFile = open(newFilePath, "a+", encoding="utf-8")
# 把旧文件的内容写入到新文件中
oldFile.seek(0)
newFile.write(oldFile.read()) # 只能是文本文件
print("备份完成!")
newFile.close()
oldFile.close()
6.文件分类存档
import time
import os
# 获取年月日
def getNowTime():
return time.strftime("%Y%m%d", time.localtime())
'''
oldFileName : 旧文件名称
path : 旧文件路径
newPath : 新文件路径
dirs : 创建的文件夹集合
'''
def saveFile(oldFileName, path, newPath, dirs):
# 获取文件后缀
hz = oldFileName[oldFileName.rfind(".")+1:]
# 获取文件名称
fn = oldFileName[:oldFileName.rfind(".")]
for i in dirs: # 在文件夹集合中遍历
if hz == i: # 当前文件后缀如果跟集合中的名称一致
# 保存文件
with open(path+"\"+oldFileName, "rb") as f:
rf = f.read()
nf = newPath + "\" + i + "\" + fn + getNowTime()+"."+hz
with open(nf, "wb") as wf:
wf.write(rf)
break # 退出循环
# 根据指定目录读取所有文件
path = r"D:所有文件"
newPath = r"D:所有文件分类存档"
if not os.path.exists(newPath):
os.mkdir(newPath)
files = os.listdir(path)
dirs = set() # 创建set集合,保存不同文件的后缀
for fileName in files:
hz = fileName[fileName.rfind(".")+1:]
dirs.add(hz)
# # 根据分类创建文件夹
for i in dirs:
p = newPath+"\"+i
os.mkdir(p)
# 再次循环遍历,将不同文件后缀放入到对应的文件夹中
for fileName in files:
saveFile(fileName, path, newPath, dirs)
# 循环遍历所有文件分类存档 文件夹的所有内容
for fileName in os.listdir(newPath):
abs_path = os.path.join(newPath, fileName)
if os.path.isdir(abs_path):
print(fileName+":", end=" ")
ffs = os.listdir(abs_path)
for f1 in ffs:
print(f1, end=" 、 ")
print()



