在Python中,正确处理文件名和路径是进行高效文件操作的基础。本文将详细介绍如何使用Python标准库中的os和pathlib模块来处理文件名和路径,包括文件路径的拼接、目录的创建、文件的读取和写入...
在Python中,正确处理文件名和路径是进行高效文件操作的基础。本文将详细介绍如何使用Python标准库中的os和pathlib模块来处理文件名和路径,包括文件路径的拼接、目录的创建、文件的读取和写入等操作。
在Python中,文件路径用于标识文件在文件系统中的位置。路径可以是绝对路径,也可以是相对路径。
/home/user/documents/file.txt。documents/file.txt。os模块处理文件路径os模块是Python标准库中用于处理文件和目录的模块。
import os
current_directory = os.getcwd()
print("当前工作目录:", current_directory)file_path = os.path.join(current_directory, 'documents', 'file.txt')
print("文件路径:", file_path)os.makedirs('new_directory', exist_ok=True)
print("目录创建成功:", 'new_directory')directory_content = os.listdir('new_directory')
print("目录内容:", directory_content)import shutil
shutil.rmtree('new_directory')
print("目录删除成功:", 'new_directory')pathlib模块处理文件路径pathlib模块是Python 3.4及以上版本中引入的,它提供了一个面向对象的方式来处理文件系统路径。
Path对象from pathlib import Path
path = Path('new_directory')
print("Path对象:", path)print("文件名:", path.name)
print("扩展名:", path.suffix)print("绝对路径:", path.resolve())path.mkdir(parents=True, exist_ok=True)
print("目录创建成功:", 'new_directory')print("目录内容:", list(path.iterdir()))path.rmdir()
print("目录删除成功:", 'new_directory')with open('file.txt', 'r') as file: content = file.read() print("文件内容:", content)with open('file.txt', 'w') as file: file.write("这是新内容")掌握Python中文件名与路径的处理方法对于高效地进行文件操作至关重要。通过使用os和pathlib模块,你可以轻松地管理文件和目录,实现各种文件操作任务。