python,os操作文件,文件路径

最近看到python的os模块,以及os,os.path的具体用法,有些不明白,在此记录一下。
概念:python获取文件的上一级目录:取文件所在目录的上一级目录
os.path.pardir:是父目录,
os.path.abspath:是获取绝对路径
具体的举个例子看一下:
实验文件的真实绝路径为:D:\Python\test.py,现在运行test.py文件,python test.py。测试代码如下:

import os ,os.path
print os.path.abspath("__file__")  # 获取当前文件的绝对路径
print os.path.dirname(os.path.abspath("__file__")) # 获取当前文件所在的目录名称
print os.path.pardir # 获取相对于文件当前目录的上级目录
print os.path.abspath(os.path.pardir)  # 获取相对于文件当前目录的上级目录的绝对路径
print os.path.join(os.path.dirname("__file__"),os.path.pardir) # 将文件的当前目录和文件当前目录的上级目录进行合并,取交集
print os.path.abspath(os.path.join(os.path.dirname("__file__"),os.path.pardir))

# 对应的输出为:
D:\Python\__file__
D:\Python
..   # “..”这是上级目录的表示方法
D:\
..  # 取 D:\Python\__file__ 和 D:\的交集,就是D:\,也就是"..",还是os.path.pardir的值。也就是文件当前目录的上一级(父级)目录。
D:\  # 也就是获取".."的绝对路径。

还有几个常见的命令:
python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。
得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()
返回指定目录下的所有文件和目录名:os.listdir()
函数用来删除一个文件:os.remove()
删除多个目录:os.removedirs(r“c:\python”)
检验给出的路径是否是一个文件:os.path.isfile()
检验给出的路径是否是一个目录:os.path.isdir()
判断是否是绝对路径:os.path.isabs()
检验给出的路径是否真地存:os.path.exists()
返回一个路径的目录名和文件名:os.path.split() eg os.path.split(‘/home/swaroop/byte/code/poem.txt’) 结果:(‘/home/swaroop/byte/code’, ‘poem.txt’)

分离扩展名:os.path.splitext()
获取路径名:os.path.dirname()
获取文件名:os.path.basename()
运行shell命令: os.system()
读取和设置环境变量:os.getenv() 与os.putenv()
给出当前平台使用的行终止符:os.linesep Windows使用’\r\n’,Linux使用’\n’而Mac使用’\r’
指示你正在使用的平台:os.name 对于Windows,它是’nt’,而对于Linux/Unix用户,它是’posix’
重命名:os.rename(old, new)
创建多级目录:os.makedirs(r“c:\python\test”)
创建单个目录:os.mkdir(“test”)
获取文件属性:os.stat(file)
修改文件权限与时间戳:os.chmod(file)
终止当前进程:os.exit()
获取文件大小:os.path.getsize(filename)

参考网址:http://blog.csdn.net/longshenlmj/article/details/13294871

下面结合具体的代码来解释一下它们的应用:

import os,os.path as osp
def check_dir(path):  
    """ make sure the dir specified by path got created """
    d = osp.abspath(osp.join(path, osp.pardir))
    if not osp.exists(d):
        os.makedirs(d)

# 代码调用:

猜你喜欢

转载自blog.csdn.net/xiongchengluo1129/article/details/79181246