python脚本中遇到的一些指令

获取当前目录和上级目录

http://blog.csdn.net/leorx01/article/details/71141643

import os
获取当前目录
os.getcwd()
os.path.abspath(os.path.dirname(__file__))

获取上级目录
os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
os.path.abspath(os.path.dirname(os.getcwd()))
os.path.abspath(os.path.join(os.getcwd(), ".."))

获取上上级目录
os.path.abspath(os.path.join(os.getcwd(), "../.."))

python逐行读取文件的内容,并写入其他某个文件中

    os.system('touch '+current_dir+'/a.txt')
    # 找的是site-packages的位置,并写入a.txt
    os.system('find / -name site-packages >> '+current_dir+'/a.txt')
    f = open(current_dir+'/a.txt')
    # linesa 是所有的site-packages的位置
    linesa = f.readlines()
    for linea in linesa:
        # 对于其中一个
        linea = linea.strip()
        # 打开b.txt
        fd = open(current_dir+'/b.txt')
        # 获取b中所有的内容
        linesb = fd.readlines()
        # 打开其中一个site-packages的位置下的sitecustomize.py文件
        fd = open(linea+'/sitecustomize.py', 'w+')
        # 将b中的文件内容逐行写入sitecustomize.py中
        for lineb in linesb:
            lineb = lineb.strip()
            fd.write(lineb+'\n')
        fd.close()
    f.close()

python判断一个文件和目录是否存在

os.path.exists(filename)
os.path.isfile(filename)
os.path.isdir(dirname)

python获取shell命令的返回值

>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

python改变当前目录

os.chdir()

你可能感兴趣的:(python脚本)