import os
# 获取当前工作目录
current_directory = os.getcwd()
print(f"当前工作目录是: {current_directory}")
# 创建新目录
new_directory = "new_folder"
if not os.path.exists(new_directory):
os.makedirs(new_directory)
print(f"创建了新目录: {new_directory}")
# 列出指定目录下的所有文件和子目录
directory_content = os.listdir(current_directory)
print(f"当前目录下的内容: {directory_content}")
# 删除目录
# 注意:删除目录时要确保它是空的,否则会抛出异常
# os.rmdir(new_directory) # 如果需要删除,请取消注释
# 更改当前工作目录
os.chdir(new_directory)
print(f"当前工作目录已更改为: {os.getcwd()}")
# 获取文件的绝对路径
file_name = "example.txt"
absolute_path = os.path.abspath(file_name)
print(f"文件的绝对路径是: {absolute_path}")
# 检查路径是否存在
path_to_check = "non_existent_file.txt"
if os.path.exists(path_to_check):
print(f"{path_to_check} 存在")
else:
print(f"{path_to_check} 不存在")
# 检查是否为文件或目录
print(f"是否为文件: {os.path.isfile(absolute_path)}")
print(f"是否为目录: {os.path.isdir(new_directory)}")
# 获取文件大小(以字节为单位)
if os.path.isfile(absolute_path):
file_size = os.path.getsize(absolute_path)
print(f"文件大小是: {file_size} 字节")
# 删除文件
# os.remove("example.txt") # 如果需要删除,请取消注释
# 获取环境变量
environment_variable = os.getenv("PATH")
print(f"环境变量 PATH 的值是: {environment_variable}")
os.getcwd()
: 获取当前工作目录。os.makedirs()
: 创建一个新的目录(如果它不存在)。os.listdir()
: 列出指定目录下的所有文件和子目录。os.rmdir()
: 删除一个空目录。os.chdir()
: 更改当前工作目录。os.path.abspath()
: 获取文件的绝对路径。os.path.exists()
: 检查路径是否存在。os.path.isfile()
和 os.path.isdir()
: 分别检查路径是否为文件或目录。os.path.getsize()
: 获取文件大小(以字节为单位)。os.remove()
: 删除文件。os.getenv()
: 获取环境变量的值。这些函数可以帮助你在 Python 中进行常见的文件和目录操作。
上一篇:python config
下一篇:python引入库的方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站