os模块常用函数

#同样,运行后重新打开文件查看变化
import os
'''
with open ('C:\\Users\\Administrator\\Desktop\\text\\kk.txt','r') as f:
    lines = f.readlines()

with open('C:\\Users\\Administrator\\Desktop\\text\\test_new.txt','w') as new:  # 新建一个文档
    for line in lines:
        print(line)
        if line not in ['0\n','1\n']:
            new.write(line)
'''
# 可以先运行一次代码,然后,再将下面代码的注释取消,再运行一次。
#os.replace('C:\\Users\\Administrator\\Desktop\\text\\test_new.txt', 'C:\\Users\\Administrator\\Desktop\\text\\test1.txt')  # 语法:os.replace(file1,file2),将file1重命名为file2,将其替代。

# 请你根据上面的方法,将之前的代码改为用模块 os 实现(可选文档poem2)。
# 在改代码之前,可以先将上面的代码注释,然后取消下面代码的注释。

list_test = ['一弦一柱思华年。\n','只是当时已惘然。\n']

with open ('C:\\Users\\Administrator\\Desktop\\text\\test_new.txt','r') as f:
    lines = f.readlines()

with open('C:\\Users\\Administrator\\Desktop\\text\\poem2.txt','w') as new:
    for line in lines:
        if line in list_test:
            new.write('____________。\n')
        else:
            new.write(line)
a=os.getcwd()#os.getcwd()返回当前工作目录
print(a)

b=os.listdir('C:\\Users\\Administrator\\Desktop\\text')   # 返回path指定的文件夹包含的文件或文件夹的名字的列表
print(b)

#os.mkdir('C:\\Users\\Administrator\\Desktop\\text\\book')  # 创建文件夹

c=os.path.abspath('kk.txt')   # 返回绝对路径os.path.abspath(path)
print(c)

d=os.path.basename('C:\\Users\\Administrator\\Desktop\\text\\poem2.txt')   # 返回文件名
print(d)

#os.path.isfile(path)   # 判断路径是否为文件
#os.path.isdir(path)   # 判断路径是否为目录
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值