欢迎访问宙启技术站
智能推送

使用Python获取路径相关信息的简便方法

发布时间:2023-12-27 17:19:53

在Python中,可以使用os模块来获取路径相关的信息。下面是一些常用的路径操作方法和例子:

1. 获取当前工作目录:os.getcwd()

示例:

   import os
   
   current_dir = os.getcwd()
   print("当前工作目录:", current_dir)
   

2. 获取指定路径的绝对路径:os.path.abspath(path)

示例:

   import os
   
   file_path = "example.txt"
   absolute_path = os.path.abspath(file_path)
   print("绝对路径:", absolute_path)
   

3. 拼接路径:os.path.join(path1, path2, ...)

示例:

   import os
   
   dir_path = "/path/to/dir"
   file_name = "example.txt"
   file_path = os.path.join(dir_path, file_name)
   print("拼接后的路径:", file_path)
   

4. 获取路径的目录部分:os.path.dirname(path)

示例:

   import os
   
   file_path = "/path/to/dir/example.txt"
   dir_path = os.path.dirname(file_path)
   print("目录部分:", dir_path)
   

5. 获取路径的文件名部分:os.path.basename(path)

示例:

   import os
   
   file_path = "/path/to/dir/example.txt"
   file_name = os.path.basename(file_path)
   print("文件名部分:", file_name)
   

6. 判断路径是否存在:os.path.exists(path)

示例:

   import os
   
   file_path = "/path/to/dir/example.txt"
   exists = os.path.exists(file_path)
   print("路径存在:", exists)
   

7. 判断路径是否为文件:os.path.isfile(path)

示例:

   import os
   
   file_path = "/path/to/dir/example.txt"
   is_file = os.path.isfile(file_path)
   print("是文件:", is_file)
   

8. 判断路径是否为目录:os.path.isdir(path)

示例:

   import os
   
   dir_path = "/path/to/dir"
   is_dir = os.path.isdir(dir_path)
   print("是目录:", is_dir)
   

9. 获取文件大小(字节数):os.path.getsize(path)

示例:

   import os
   
   file_path = "/path/to/dir/example.txt"
   file_size = os.path.getsize(file_path)
   print("文件大小(字节数):", file_size)
   

10. 获取文件的访问时间:os.path.getatime(path)

获取文件的创建时间:os.path.getctime(path)

获取文件的修改时间:os.path.getmtime(path)

示例:

    import os
    import time
    
    file_path = "/path/to/dir/example.txt"
    access_time = os.path.getatime(file_path)
    create_time = os.path.getctime(file_path)
    modify_time = os.path.getmtime(file_path)
    
    print("访问时间:", time.ctime(access_time))
    print("创建时间:", time.ctime(create_time))
    print("修改时间:", time.ctime(modify_time))