如何使用Python的os模块对文件和目录进行操作?
发布时间:2023-12-07 15:13:24
Python的os模块提供了对文件和目录进行操作的功能。它包含了一系列函数,可以创建、删除、移动和复制文件和目录,以及查找文件和目录。
1. 导入os模块
首先要导入os模块,通过import语句将其引入到Python程序中。
import os
2. 获取当前工作目录
使用os.getcwd()函数可以获取当前的工作目录。
current_dir = os.getcwd()
print("当前工作目录:", current_dir)
3. 创建目录
使用os.mkdir()函数可以创建一个新的目录。
new_dir = "new_directory" os.mkdir(new_dir)
4. 切换工作目录
使用os.chdir()函数可以切换到指定的工作目录。
target_dir = "/path/to/target_directory" os.chdir(target_dir)
5. 列出目录内容
使用os.listdir()函数可以列出目录中的文件和子目录。
contents = os.listdir(target_dir)
for item in contents:
print(item)
6. 获取文件属性
使用os.stat()函数可以获取文件的属性,如文件大小、创建时间等。
file_path = "/path/to/file"
file_stat = os.stat(file_path)
print("文件大小:", file_stat.st_size, "bytes")
print("创建时间:", file_stat.st_ctime)
7. 复制文件
使用shutil库的shutil.copy()函数可以复制文件。
import shutil src_file = "/path/to/source_file" dest_file = "/path/to/destination_file" shutil.copy(src_file, dest_file)
8. 移动文件
使用shutil库的shutil.move()函数可以移动文件。
src_file = "/path/to/source_file" dest_dir = "/path/to/destination_directory" shutil.move(src_file, dest_dir)
9. 删除文件
使用os.remove()函数可以删除文件。
file_to_delete = "/path/to/file" os.remove(file_to_delete)
10. 删除目录
使用os.rmdir()函数可以删除空目录。
dir_to_delete = "/path/to/directory" os.rmdir(dir_to_delete)
11. 递归删除目录
使用shutil库的shutil.rmtree()函数可以递归删除目录及其内容。
dir_to_delete = "/path/to/directory" shutil.rmtree(dir_to_delete)
12. 判断文件或目录是否存在
使用os.path.exists()函数可以判断文件或目录是否存在。
path_to_check = "/path/to/file_or_directory"
if os.path.exists(path_to_check):
print(path_to_check, "存在")
else:
print(path_to_check, "不存在")
综上所述,通过Python的os模块,我们可以方便地对文件和目录进行各种操作,从而实现文件和目录的管理和处理。
