Python:目录、文件操作函数
在 Python 中,可以使用内置的os和shutil模块来进行目录和文件操作。
一、目录操作
1. os.mkdir(path):创建一个目录。
示例:os.mkdir('new_directory') 创建一个名为“new_directory”的目录。
2. os.makedirs(path, exist_ok=False):递归地创建目录,包括中间的所有目录。
exist_ok=True时,如果目录已存在则不会引发错误。
示例:os.makedirs('parent/child', exist_ok=True) 创建“parent”目录及其子目录“child”。
3. os.rmdir(path):删除一个空目录。
示例:os.rmdir('new_directory') 删除之前创建的空目录。
4. os.removedirs(path):递归地删除目录,从最深层的子目录开始删除,直到指定的目录。如果目录不为空,会引发OSError。
示例:os.removedirs('parent/child'),如果“parent/child”为空目录结构,则会被删除。
5. os.listdir(path='.'):列出指定目录下的所有文件和子目录。
示例:files_and_dirs = os.listdir() 返回当前目录下的文件和目录列表。
6. os.chdir(path):改变当前工作目录。
示例:os.chdir('new_directory') 将当前工作目录切换到“new_directory”。
7. os.getcwd():获取当前工作目录的路径。
示例:current_directory = os.getcwd() 返回当前工作目录的完整路径。
二、文件操作
1. open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):打开一个文件,并返回一个文件对象。
mode参数可以是'r'(只读)、'w'(只写,覆盖原有内容)、'a'(追加)等。
示例:
with open('file.txt', 'w') as f: f.write('Hello, world!') with open('file.txt', 'r') as f: content = f.read() print(content)
2. os.rename(src, dst):重命名文件或目录。
示例:os.rename('old_name.txt', 'new_name.txt') 将文件重命名。
3. os.remove(path):删除一个文件。
示例:os.remove('file_to_delete.txt') 删除指定文件。
4. shutil.copy(src, dst):复制文件。
示例:shutil.copy('source.txt', 'destination.txt') 将“source.txt”复制为“destination.txt”。
5. shutil.move(src, dst):移动文件或目录。
示例:shutil.move('file.txt', 'new_directory/file.txt') 将文件移动到指定目录。
6. os.path.exists(path):检查一个路径是否存在(文件或目录)。
示例:if os.path.exists('file.txt'): print('File exists.')。
7. os.path.isfile(path):检查一个路径是否是一个文件。
示例:if os.path.isfile('file.txt'): print('It is a file.')。
8. os.path.isdir(path):检查一个路径是否是一个目录。
示例:if os.path.isdir('directory'): print('It is a directory.')。
以下是一个综合运用 Python 中目录和文件操作函数的例子:
import os import shutil # 创建目录 os.makedirs('parent_directory/child_directory', exist_ok=True) # 获取当前工作目录 current_dir = os.getcwd() print(f"当前工作目录:{current_dir}") # 切换工作目录到新创建的目录 os.chdir('parent_directory') new_current_dir = os.getcwd() print(f"切换后工作目录:{new_current_dir}") # 在新目录下创建文件 with open('new_file.txt', 'w') as f: f.write('这是一个新文件的内容。') # 列出当前目录下的文件和子目录 files_and_dirs = os.listdir() print(f"当前目录下的文件和子目录:{files_and_dirs}") # 检查文件是否存在 if os.path.exists('new_file.txt'): print("文件 new_file.txt 存在。") # 检查是否是文件 if os.path.isfile('new_file.txt'): print("new_file.txt 是一个文件。") # 检查是否是目录 if os.path.isdir('child_directory'): print("child_directory 是一个目录。") # 复制文件 shutil.copy('new_file.txt', 'child_directory/copied_file.txt') # 重命名文件 os.rename('new_file.txt', 'renamed_file.txt') # 移动文件 shutil.move('renamed_file.txt', 'child_directory/renamed_file.txt') # 删除文件 os.remove('child_directory/copied_file.txt') # 返回上级目录 os.chdir('..') # 删除目录(递归删除子目录和文件) shutil.rmtree('parent_directory')
这个例子涵盖了创建目录、切换工作目录、创建文件、列出目录内容、检查文件和目录的存在性、复制、重命名、移动和删除文件以及删除目录等操作。在实际运行时,请谨慎使用删除操作,确保不会误删重要数据。