在Python中处理文件路径是一个常见的任务,尤其是在进行文件读写操作时,Python提供了多种方法来处理文件路径,包括使用内置的os
模块和pathlib
模块,以下是详细的介绍和示例代码。
使用 `os` 模块
1.1 导入模块
import os
1.2 获取当前工作目录
current_directory = os.getcwd() print(f"Current Working Directory: {current_directory}")
1.3 拼接路径
file_name = "example.txt" full_path = os.path.join(current_directory, file_name) print(f"Full Path: {full_path}")
1.4 检查路径是否存在
if os.path.exists(full_path): print("File exists") else: print("File does not exist")
1.5 创建目录
new_directory = os.path.join(current_directory, "new_folder") os.makedirs(new_directory, exist_ok=True) print(f"New directory created at: {new_directory}")
1.6 列出目录内容
contents = os.listdir(current_directory) print(f"Contents of the current directory: {contents}")
使用 `pathlib` 模块
2.1 导入模块
from pathlib import Path
2.2 获取当前工作目录
current_directory = Path.cwd() print(f"Current Working Directory: {current_directory}")
2.3 拼接路径
file_name = "example.txt" full_path = current_directory / file_name print(f"Full Path: {full_path}")
2.4 检查路径是否存在
if full_path.exists(): print("File exists") else: print("File does not exist")
2.5 创建目录
new_directory = current_directory / "new_folder" new_directory.mkdir(parents=True, exist_ok=True) print(f"New directory created at: {new_directory}")
2.6 列出目录内容
contents = list(current_directory.iterdir()) print(f"Contents of the current directory: {contents}")
功能 | os 模块 | pathlib 模块 |
获取当前工作目录 | os.getcwd() | Path.cwd() |
拼接路径 | os.path.join() | / |
检查路径是否存在 | os.path.exists() | Path.exists() |
创建目录 | os.makedirs() | Path.mkdir() |
列出目录内容 | os.listdir() | Path.iterdir() |
示例代码汇总
import os from pathlib import Path Using os module current_directory = os.getcwd() print(f"Current Working Directory (os): {current_directory}") file_name = "example.txt" full_path = os.path.join(current_directory, file_name) print(f"Full Path (os): {full_path}") if os.path.exists(full_path): print("File exists (os)") else: print("File does not exist (os)") new_directory = os.path.join(current_directory, "new_folder") os.makedirs(new_directory, exist_ok=True) print(f"New directory created at (os): {new_directory}") contents = os.listdir(current_directory) print(f"Contents of the current directory (os): {contents}") Using pathlib module current_directory = Path.cwd() print(f"Current Working Directory (pathlib): {current_directory}") file_name = "example.txt" full_path = current_directory / file_name print(f"Full Path (pathlib): {full_path}") if full_path.exists(): print("File exists (pathlib)") else: print("File does not exist (pathlib)") new_directory = current_directory / "new_folder" new_directory.mkdir(parents=True, exist_ok=True) print(f"New directory created at (pathlib): {new_directory}") contents = list(current_directory.iterdir()) print(f"Contents of the current directory (pathlib): {contents}")
通过上述方法和示例代码,你可以灵活地处理文件路径,选择适合你需求的方法。
以上就是关于“python处理文件路径 _Python文件”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/84715.html