OS库path子库的使用

一、路径字符串处理

  1. os.path.abspath(path):返回path在当前系统中的绝对路径
    print(os.path.abspath("test.py"))
    # output:F:\1-Sutdy-Computer-Python\Python-Project\Scrapy_basis\test.py
    
  2. os.path.normpath(path):规格化路径,将路径全部转化为反斜杠\分隔
    print(os.path.normpath(r"F:/1-Study-Computer-Python/Python-Project/Scrapy_basis/test.py"))
    # output:F:\1-Study-Computer-Python\Python-Project\Scrapy_basis\test.py
    
  3. os.path.relpath(path):返回当前程序与path文件的相对路径
    path = os.path.abspath("../BookManagerSystem")
    print(path)
    print(os.path.relpath(path))
    # output1: F:\1-Study-Computer-Python\Python-Project\BookManagerSystem
    # output2: ..\BookManagerSystem
    
  4. os.path.dirname(path):返回path字符串中的文件夹名称
    print(os.path.dirname(r"F:\1-Study-Computer-Python\Python-Project\Scrapy_basis\test.py"))
    # output: F:\1-Study-Computer-Python\Python-Project\Scrapy_basis
    
  5. os.path.basename(path):返回path字符串中的文件名称
    print(os.path.basename(r"F:\1-Study-Computer-Python\Python-Project\Scrapy_basis\test.py"))
    # output: test.py
    
  6. os.path.join(path,* paths):组合path和*paths,返回新的路径
    print(os.path.join(r"F:\1-Study-Computer-Python\Python-Project\Scrapy_basis", r"test.py"))
    # output: F:\1-Study-Computer-Python\Python-Project\Scrapy_basis\test.py
    
    

二、路径对应文件判断

  1. os.path.exists(path):判断path对应文件或目录是否存在,返回True或False
    print(os.path.exists("test_os_path.py"))
    # output: True
    
  2. os.path.isfile(path):判断path所对应是否为已存在的文件,返回True或False
    print(os.path.isfile("test_os_path.py"))
    # output: True
    
  3. os.path.isdir(path):判断path所对应是否为已存在的目录,返回True或False
    print(os.path.isdir("test_os_path.py"))
    # output: False
    

三、路径对应文件信息

  1. os.path.getatime(path): 返回path对应文件或目录上一次的访问时间

  2. os.path.getmtime(path):返回path对应文件或目录最近一次的修改时间

  3. os.path.getctime(path) :返回path对应文件或目录的创建时间

  4. os.path.getsize(path):返回path对应文件的大小,以字节为单位

### Python中`os`使用 #### 导入模块 为了使用`os`的功能,需要先导入该模块。这可以通过简单的import语句完成。 ```python import os ``` #### 获取当前工作目录 获取程序执行时所在的默认位置即为当前工作目录,这对于相对路径的操作非常重要[^2]。 ```python current_directory = os.getcwd() print(f"Current Working Directory is {current_directory}") ``` #### 列出指定目录下的文件和目录名 可以利用`listdir()`函数来查看某个特定文件夹里面的内容列表[^1]。 ```python files_and_directories = os.listdir(current_directory) for item in files_and_directories: print(item) ``` #### 创建新目录 如果想要创建一个新的文件夹,则可调用`mkdir()`方法;对于多层嵌套结构则应该采用`makedirs()`[^3]。 ```python try: os.mkdir('test_folder') except FileExistsError as e: print(e) # For nested directories use makedirs instead of mkdir. try: os.makedirs('nested/test/folder') except FileExistsError as e: print(e) ``` #### 删除目录 当不再需要某些空文件夹的时候,就可以通过`rmdir()`命令将其移除;而要删除整个树状结构的话就应当选用`removedirs()`。 ```python os.rmdir('test_folder') # Only works on empty folders. # Remove entire directory tree if it's empty from bottom up. os.removedirs('nested/test/folder') ``` #### 检查文件或目录的存在性和属性 有时可能想知道某项资源是否存在以及它的具体性质是什么样的——比如是不是一个普通的文件?这时就有必要借助于`path`模块下的一些辅助性的判定接口了,像`exists()`, `isfile()`, 和 `isdir()`等[^4]。 ```python file_path = r'C:\Users\example_user\documents\example_file.txt' if os.path.exists(file_path): if os.path.isfile(file_path): print("It's a file.") elif os.path.isdir(file_path): print("It's a directory.") else: print("The path does not exist.") ``` #### 更改当前的工作目录 改变脚本运行期间所处的位置到另一个地方去,可以用`chdir()`来做切换动作。 ```python target_dir = '/home/user/new_location' os.chdir(target_dir) new_current_directory = os.getcwd() print(f"Now working at: {new_current_directory}") ``` 以上就是关于Python内置`os`的基础介绍及其部分核心API的应用实例展示。希望这些信息能帮助理解并掌握这个强大的工具集,在日常开发过程中更加得心应手地处理各种与操作系统有关的任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值