1. 介绍

Python中对文件和目录的操作的模块有:os、fileinput、tempfile、shutil,它们的作用分别如下:

  • os: 提供与操作系统相关的功能,本篇只介绍和文件、目录相关的部分。
  • fileinput: 实现了一个辅助类和一些函数用来快速编写访问标准输入或文件列表的循环
  • tempfile: 该模块用于创建临时文件和目录,它可以跨平台使用
  • shutil: 模块提供了一系列对文件和文件集合的高阶操作。 特别是提供了一些支持文件拷贝和删除的函数。

@注:上述这些模块,支持的功能有很多,本篇只学习和文件相关的操作,更多功能可自行查看官网文档:https://docs.python.org/zh-cn/3/library/index.html:>

2. 文件操作

2.1 判断和创建

import os

if __name__ == '__main__':
# 当前目录
print("当前目录:", os.getcwd())
# 列出当前目录下所有文件
print("当前目录下所有文件:", os.listdir(os.getcwd()))
# 拼接文件
filePath = os.path.join(os.getcwd(), "test.txt")
print("文件位置:", filePath)
# 判断文件是否存在
b = os.path.exists(filePath)
print("判断文件是否存在:", b)
if not b:
print("文件:{}, 不存在".format(filePath))
# 创建文件
open(filePath, "w").close()

print("当前目录下所有文件(创建后):", os.listdir(os.getcwd()))

# ---------------------------- 输出 ---------------------------
当前目录: /Users/liuqh/ProjectItem/PythonItem/fast-use-ai/test
当前目录下所有文件: ['__pycache__', 'localTest.py']
文件位置: /Users/liuqh/ProjectItem/PythonItem/fast-use-ai/test/test.txt
判断文件是否存在: False
文件:/Users/liuqh/ProjectItem/PythonItem/fast-use-ai/test/test.txt, 不存在
当前目录下所有文件(创建后): ['__pycache__', 'localTest.py', 'test.txt']

2.2 打开文件

import os

if __name__ == '__main__':
# 拼接文件
filePath = os.path.join(os.getcwd(), "test.txt")
# 打开前先判断是否存在
if not os.path.exists(filePath):
print("文件不存在~")
exit()
# 打开文件
with open(filePath) as f:
print("f.mode:", f.mode)
print("f.name:", f.name)

# ---------------------------- 输出 ---------------------------
f.mode: r
f.name: /Users/liuqh/ProjectItem/PythonItem/fast-use-ai/test/test.txt

@注: 使用with打开文件,会自动调用close方法关闭资源,推荐使用。

2.3 文件信息

if __name__ == '__main__':
# 拼接文件
filePath = os.path.join(os.getcwd(), "test.txt")
# 打开前先判断是否存在
if not os.path.exists(filePath):
print("文件不存在~")
exit()
# 文件信息
print("文件信息:", os.stat(filePath))
# --------------------- 输出 ----------------
文件信息: os.stat_result(st_mode=33188, st_ino=93754300, st_dev=16777220, st_nlink=1, st_uid=502, st_gid=20, st_size=0, st_atime=1692889555, st_mtime=1692889555, st_ctime=1692889555)
字段 说明
st_mode 文件模式
st_ino 与平台有关,如果不为零,则根据 st_dev 值唯一地标识文件
st_dev 该文件所在设备的标识符。
st_nlink 硬链接的数量
st_uid 文件所有者的用户 ID
st_gid 文件所有者的用户组 ID
st_size 文件大小(以字节为单位)
st_atime 最近的访问时间,以秒为单位
st_mtime 最近的修改时间,以秒为单位

2.4 读写文件

if __name__ == '__main__':
# 拼接文件
filePath = os.path.join(os.getcwd(), "test.txt")
# 打开前先判断是否存在
if not os.path.exists(filePath):
print("文件不存在~")
exit()

print("------------- 写入文件 -------------------")
# 以写模式,打开文件
with open(filePath, "w") as f:
for line in range(3):
# 写入字符串
f.write("Hello world \n")
# 写入字符串列表
f.writelines(["GoGoGoGo" + str(line), "\n"])

print("------------- 读取文件 -------------------")
# 以读模式,打开文件
with open(filePath, "r") as f:
# 一次性读取
print("---- 一次性读取所有 ---")
print("一次性读取:", f.read())

with open(filePath, "r") as f:
print("---- 每次读取一行 ---")
for line in range(7):
print("读取第 %s 行:" % line, f.readline())

with open(filePath, "r") as f:
print("---- 读取所有,返回是列表 ---")
print("读取所有:", f.readlines())

# --------------------- 输出 ----------------

------------- 写入文件 -------------------
------------- 读取文件 -------------------
---- 一次性读取所有 ---
一次性读取: Hello world
GoGoGoGo0
Hello world
GoGoGoGo1
Hello world
GoGoGoGo2

---- 每次读取一行 ---
读取第 0 行: Hello world

读取第 1 行: GoGoGoGo0

读取第 2 行: Hello world

读取第 3 行: GoGoGoGo1

读取第 4 行: Hello world

读取第 5 行: GoGoGoGo2

读取第 6 行:
---- 读取所有,返回是列表 ---
读取所有: ['Hello world \n', 'GoGoGoGo0\n', 'Hello world \n', 'GoGoGoGo1\n', 'Hello world \n', 'GoGoGoGo2\n']

2.5 改名和删除

if __name__ == '__main__':
# 拼接文件
filePath = os.path.join(os.getcwd(), "test.txt")
# 打开前先判断是否存在
if not os.path.exists(filePath):
print("文件不存在~")
exit()

# 改名前
print("改名前-当前目录下所有文件:", os.listdir(os.getcwd()))
# 把文件test.txt 改名为 abc.txt
os.rename("test.txt", "abc.txt")
print("改名后-当前目录下所有文件:", os.listdir(os.getcwd()))

# 删除文件
os.remove("abc.txt")
print("删除后-当前目录下所有文件:", os.listdir(os.getcwd()))

# --------------------- 输出 ----------------
改名前-当前目录下所有文件: ['__pycache__', 'localTest.py', 'test.txt']
改名后-当前目录下所有文件: ['abc.txt', '__pycache__', 'localTest.py']
删除后-当前目录下所有文件: ['__pycache__', 'localTest.py']

2.6 复制和移动

import os
import shutil

if __name__ == '__main__':
fileName = "./test.txt"
exist = os.path.exists(fileName)
if not exist:
print("文件不存在,准备创建~")
# 创建文件
open(fileName, "w").close()

# 复制文件
dstName = "./test-new.txt"
shutil.copyfile(fileName, dstName)
# 移动文件
shutil.move(fileName, "./a/test.txt")

@注意: 使用shutil.move移动文件时,目标目录不存在则会报错。

3.目录操作

3.1 判断和创建

if __name__ == '__main__':
print("当前目录下所有文件和目录A:", os.listdir(os.getcwd()))
dirName = "./abc/test"
exist = os.path.exists(dirName)
if not exist:
print("目录不存在~")
# 递归创建
os.makedirs(dirName)

print("当前目录下所有文件和目录B:", os.listdir(os.getcwd()))

dirName2 = "./demo"
if not os.path.exists(dirName2):
print("目录不存在~")
# 创建
os.mkdir(dirName2)

print("当前目录下所有文件和目录:", os.listdir(os.getcwd()))

# --------------------- 输出 ----------------
当前目录下所有文件和目录A: ['__pycache__', 'a', 'localTest.py']
目录不存在~
当前目录下所有文件和目录B: ['abc', '__pycache__', 'a', 'localTest.py']
目录不存在~
当前目录下所有文件和目录: ['demo', 'abc', '__pycache__', 'a', 'localTest.py']

3.2 当前目录

if __name__ == '__main__':
print("当前目录:", os.getcwd())
print("当前目录下所有文件和目录:", os.listdir(os.getcwd()))
# --------------------- 输出 ----------------
当前目录: /Users/liuqh/ProjectItem/PythonItem/fast-use-ai/test
当前目录下所有文件和目录: ['__pycache__', 'localTest.py', 'testdir']

3.3 递归删除

import os
import shutil

if __name__ == '__main__':
pathNameA = os.path.join(os.getcwd(), "a")
pathNameB = os.path.join(os.getcwd(), "b")
print(pathNameA)
print(pathNameB)
shutil.rmtree(pathNameA)
shutil.rmtree(pathNameB)

@注: 目录下有文件时,执行shutil.rmtree也会被删除

3.4 切换工作目录

import os
import shutil

if __name__ == '__main__':
print("当前工作目录:", os.getcwd())
# 切换工作目录
os.chdir(os.path.join(os.getcwd(), "demo"))
print("切换后,当前工作目录:", os.getcwd())

# --------------------- 输出 ----------------
当前工作目录: /Users/liuqh/ProjectItem/PythonItem/fast-use-ai/test
切换后,当前工作目录: /Users/liuqh/ProjectItem/PythonItem/fast-use-ai/test/demo