Python教程介绍 日常对于批量处理文件的需求非常多,用Python写脚本可以非常方便地实现,但在这过程中难免会和文件打交道,第一次做会有很多文件的操作无从下手,只能找度娘。
|
Python教程介绍十大常用文件操作,干货满满~~
推荐(免费):Python教程(视频) 日常对于批量处理文件的需求非常多,用Python写脚本可以非常方便地实现,但在这过程中难免会和文件打交道,第一次做会有很多文件的操作无从下手,只能找度娘。 本篇东哥整理了10个Python中最常用到的文件操作,无论是批处理还是读取文件都会用到,相信这个梳理会有所帮助。 1. 显示当前目录 当我们想知道当前的工作目录是什么的时候,我们可以简单地使用 >>> # 第一种方法:显示当前目录
... import os
... print("当前工作目录:", os.getcwd())
...
Current Work Directory: /Users/ycui1/PycharmProjects/Medium_Python_Tutorials
>>> # 第二种方法:或者我们也可以使用 pathlib
... from pathlib import Path
... print("当前工作目录:", Path.cwd())
...
Current Work Directory: /Users/ycui1/PycharmProjects/Medium_Python_Tutorials如果使用的是旧版本的Python(<3.4),则必须使用该os模块。 2. 建立一个新目录 要创建目录,可以使用 >>> # 在当前文件夹创建新目录
... os.mkdir("test_folder")
... print("目录是否存在:", os.path.exists("test_folder"))
...
目录是否存在: True
>>> # 在特定文件夹创建新目录
... os.mkdir('/Users/ycui1/PycharmProjects/tmp_folder')
... print("目录是否存在:", os.path.exists('/Users/ycui1/PycharmProjects/tmp_folder'))
...
目录是否存在: True但是,如果想要建立一个多层级的目录,比如文件夹中下的文件夹),则需要使用该 >>> # 创建包含子目录的目录
... os.makedirs('tmp_level0/tmp_level1')
... print("目录是否存在:", os.path.exists("tmp_level0/tmp_level1"))
...
Is the directory there: True如果使用最新版本的Python(≥3.4),则可以考虑利用 # 使用 pathlib
from pathlib import Path
Path("test_folder").mkdir(parents=True, exist_ok=True)需要注意一个问题,如果尝试多次运行上述某些代码,可能会遇到问题“无法创建已经存在的新目录”。我们可以将 >>> # 使用 pathlib
... from pathlib import Path
... Path("test_folder").mkdir(parents=True, exist_ok=False)
...
Traceback (most recent call last):
File "<input>", line 3, in <module>
File "/Users/ycui1/.conda/envs/Medium/lib/python3.8/pathlib.py", line 1284, in mkdir
self._accessor.mkdir(self, mode)
FileExistsError: [Errno 17] File exists: 'test_folder'3. 删除目录和文件 完成对某些文件或文件夹的操作后,我们可能希望删除它。为此,我们可以使用 >>> # 删除一个文件
... print(f"* 删除文件前 {os.path.isfile('tmp.txt')}")
... os.remove('tmp.txt')
... print(f"* 删除文件后 {os.path.exists('tmp.txt')}")
...
* 删除文件前 True
* 删除文件后 False
>>> # 删除一个文件夹
... print(f"* 删除文件夹前 {os.path.isdir('tmp_folder')}")
... os.rmdir('tmp_folder')
... print(f"* 删除文件夹后 {os.path.exists('tmp_folder')}")
...
* 删除文件夹前 True
* 删除文件夹后 False如果使用 4. 获取文件列表 当我们分析某个工作或机器学习项目进行数据处理时,需要获取特定目录中的文件列表。 通常,文件名具有匹配的模式。假设我们要查找目录中的所有.txt文件,可使用Path对象的方法 >>> txt_files = list(Path('.').glob("*.txt"))
... print("Txt files:", txt_files)
...
Txt files: [PosixPath('hello_world.txt'), PosixPath('hello.txt')]另外,直接使用 >>> from glob import glob
... files = list(glob('h*'))
... print("以h开头的文件:", files)
...
Files starting with h: ['hello_world.txt', 'hello.txt']5. 移动和复制文件 移动文件 常规文件管理任务之一是移动和复制文件。在Python中,这些工作可以非常轻松地完成。要移动文件,只需将其旧目录替换为目标目录即可重命名该文件。假设我们需要将所有.txt文件移动到另一个文件夹,下面用 >>> target_folder = Path("目标文件")
... target_folder.mkdir(parents=True,exist_ok=True)
... source_folder = Path('.')
...
... txt_files = source_folder.glob('*.txt')
... for txt_file in txt_files:
... filename = txt_file.name
... target_path = target_folder.joinpath(filename)
... print(f"** 移动文件 {filename}")
... print("目标文件存在:", target_path.exists())
... txt_file.rename(target_path)
... print("目标文件存在:", target_path.exists(), '\n')
...
** 移动文件 hello_world.txt
目标文件存在: False
目标文件存在: True
** 移动文件 hello.txt
目标文件存在: False
目标文件存在: True复制文件 我们可以利用 >>> import shutil
...
... source_file = "target_folder/hello.txt"
... target_file = "hello2.txt"
... target_file_path = Path(target_file)
... print("* 复制前,文件存在:", target_file_path.exists())
... shutil.copy(source_file, target_file)
... print("* 复制后,文件存在:", target_file_path.exists())
...
* 复制前,文件存在: False
* 复制后,文件存在: True6. 检查目录/文件 上面的示例中一直在使用 # os 模块中 exists() 用法
os.path.exists('path_to_check')
# pathlib 模块中 exists() 用法
Path('directory_path').exists()使用 # 检查路径是否是目录
os.path.isdir('需要检查的路径')
Path('需要检查的路径').is_dir()
# 检查路径是否是文件
os.path.isfile('需要检查的路径')
Path('需要检查的路径').is_file()7. 获取文件信息 文件名称 处理文件时,许多情况下都需要提取文件名。使用Path非常简单,可以在Path对象上查看name属性 for py_file in Path().glob('c*.py'):
... print('Name with extension:', py_file.name)
... print('Name only:', py_file.stem)
...
带文件后缀: closures.py
只有文件名: closures
带文件后缀: counter.py
只有文件名: counter
带文件后缀: context_management.py
只有文件名: context_management文件后缀 如果想单独提取文件的后缀,可查看Path对象的 >>> file_path = Path('closures.py')
... print("文件后缀:", file_path.suffix)
...
File Extension: .py文件更多信息 如果要获取有关文件的更多信息,例如文件大小和修改时间,则可以使用该 >>> # 路径 path 对象
... current_file_path = Path('iterable_usages.py')
... file_stat = current_file_path.stat()
...
>>> # 获取文件大小:
... print("文件大小(Bytes):", file_stat.st_size)
文件大小(Bytes): 3531
>>> # 获取最近访问时间
... print("最近访问时间:", file_stat.st_atime)
最近访问时间: 1595435202.310935
>>> # 获取最近修改时间
... print("最近修改时间:", file_stat.st_mtime)
最近修改时间: 1594127561.32044178. 读取文件 最重要的文件操作之一就是从文件中读取数据。读取文件,最常规的方法是使用内置 >>> # 读取所有的文本
... with open("hello2.txt", 'r') as file:
... print(file.read())
...
Hello World!
Hello Python!
>>> # 逐行的读取
... with open("hello2.txt", 'r') as file:
... for i, line in enumerate(file, 1):
... print(f"* 读取行 #{i}: {line}")
...
* 读取行 #1: Hello World!
* 读取行 #2: Hello Python!如果文件中没有太多数据,则可以使用该 默认将文件内容视为文本。如果要使用二进制文件,则应明确指定用 另一个棘手的问题是文件的编码。在正常情况下, 9. 写入文件 仍然使用 >>> # 向文件中写入新数据
... with open("hello3.txt", 'w') as file:
... text_to_write = "Hello Files From Writing"
... file.write(text_to_write)
...
>>> # 增加一些数据
... with open("hello3.txt", 'a') as file:
... text_to_write = "\nHello Files From Appending"
... file.write(text_to_write)
...
>>> # 检查文件数据是否正确
... with open("hello3.txt") as file:
... print(file.read())
...
Hello Files From Writing
Hello Files From Appending上面每次打开文件时都使用
10. 压缩和解压缩文件 压缩文件
>>> from zipfile import ZipFile
...
... # 创建压缩文件
... with ZipFile('text_files.zip', 'w') as file:
... for txt_file in Path().glob('*.txt'):
... print(f"*添加文件: {txt_file.name} 到压缩文件")
... file.write(txt_file)
...
*添加文件: hello3.txt 到压缩文件
*添加文件: hello2.txt 到压缩文件解压缩文件 >>> # 解压缩文件
... with ZipFile('text_files.zip') as zip_file:
... zip_file.printdir()
... zip_file.extractall()
...
File Name Modified Size
hello3.txt 2020-07-30 20:29:50 51
hello2.txt 2020-07-30 18:29:52 26结论 以上就是整理的Python常用文件操作,全部使用内置函数实现。当然,也可以借助比如 以上就是总结 Python十大常用文件操作的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |
