import os
# 获取当前文件的绝对路径
current_file_path = os.path.abspath(__file__)
print(f"当前文件的绝对路径是: {current_file_path}")
# 获取当前文件所在的目录
current_directory = os.path.dirname(current_file_path)
print(f"当前文件所在的目录是: {current_directory}")
# 获取指定路径的目录内容
specified_directory = "/path/to/directory" # 替换为实际路径
directory_contents = os.listdir(specified_directory)
print(f"指定目录的内容是: {directory_contents}")
# 遍历指定目录及其子目录
for root, dirs, files in os.walk(specified_directory):
print(f"目录: {root}")
print(f"子目录: {dirs}")
print(f"文件: {files}")
os.path.abspath(__file__) 返回当前 Python 文件的绝对路径。os.path.dirname(path) 返回给定路径的目录部分。os.listdir(path) 返回指定路径下的文件和目录列表。os.walk(path) 生成目录树下的文件名,包括子目录。每次迭代返回一个三元组 (root, dirs, files),其中 root 是当前目录路径,dirs 是子目录列表,files 是文件列表。请根据实际情况替换 /path/to/directory 为你要操作的具体路径。
上一篇:rabbitmq python
下一篇:python获取list的长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站