# 示例代码:处理Python中的路径
import os
# 获取当前工作目录
current_directory = os.getcwd()
print(f"当前工作目录是: {current_directory}")
# 构建一个新的路径
new_folder = "my_new_folder"
new_path = os.path.join(current_directory, new_folder)
print(f"新路径是: {new_path}")
# 检查路径是否存在
if not os.path.exists(new_path):
# 创建新文件夹
os.makedirs(new_path)
print(f"创建了新文件夹: {new_path}")
else:
print(f"文件夹已存在: {new_path}")
# 列出指定目录下的所有文件和文件夹
files_and_folders = os.listdir(current_directory)
print(f"当前目录下的文件和文件夹: {files_and_folders}")
# 使用pathlib模块处理路径(推荐方式)
from pathlib import Path
# 获取当前工作目录
current_path = Path.cwd()
print(f"使用Pathlib获取的当前工作目录是: {current_path}")
# 构建一个新的路径
new_path_lib = current_path / new_folder
print(f"使用Pathlib构建的新路径是: {new_path_lib}")
# 检查路径是否存在
if not new_path_lib.exists():
# 创建新文件夹
new_path_lib.mkdir(parents=True, exist_ok=True)
print(f"使用Pathlib创建了新文件夹: {new_path_lib}")
else:
print(f"使用Pathlib检查到文件夹已存在: {new_path_lib}")
# 列出指定目录下的所有文件和文件夹
items = list(current_path.iterdir())
print(f"使用Pathlib列出当前目录下的文件和文件夹: {items}")
os模块:
os.getcwd()
:获取当前工作目录。os.path.join()
:用于构建跨平台的路径。os.path.exists()
:检查路径是否存在。os.makedirs()
:递归创建目录。os.listdir()
:列出指定目录下的所有文件和文件夹。pathlib模块(推荐):
Path.cwd()
:获取当前工作目录。Path /
:用于构建跨平台的路径。Path.exists()
:检查路径是否存在。Path.mkdir()
:创建目录。Path.iterdir()
:列出指定目录下的所有文件和文件夹。这两种方法都可以用来处理路径,但pathlib
模块更现代且易于使用,推荐优先使用。
下一篇:python &&
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站