Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python中os库的用法

作者:花小泽ノ   发布日期:2025-09-13   浏览:52

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}")

解释说明:

  1. os.getcwd(): 获取当前工作目录。
  2. os.makedirs(): 创建一个新的目录(如果它不存在)。
  3. os.listdir(): 列出指定目录下的所有文件和子目录。
  4. os.rmdir(): 删除一个空目录。
  5. os.chdir(): 更改当前工作目录。
  6. os.path.abspath(): 获取文件的绝对路径。
  7. os.path.exists(): 检查路径是否存在。
  8. os.path.isfile()os.path.isdir(): 分别检查路径是否为文件或目录。
  9. os.path.getsize(): 获取文件大小(以字节为单位)。
  10. os.remove(): 删除文件。
  11. os.getenv(): 获取环境变量的值。

这些函数可以帮助你在 Python 中进行常见的文件和目录操作。

上一篇:python config

下一篇:python引入库的方法

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站