python脚本中遇到的一些指令

本文介绍了使用Python进行路径操作的方法,包括获取当前目录、上级目录等,同时展示了如何逐行读取文件内容并写入其他文件,以及如何判断文件和目录是否存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取当前目录和上级目录

http://blog.youkuaiyun.com/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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值