目录及文件操作

import os

os.path.abspath('.')            # 当前IDEL所处的文件夹的绝对路径:'C:\\Program Files\\python3.9'

os.path.abspath('..')           # 当前所处的文件夹上一级文件夹的绝对路径:'C:\\Program Files

os.listdir()                           # 列出当前目录下,所有的文件夹及文件,返回一个列表

os.listdir('d:\\')                   # 列出d:\\目录下,所有的文件夹及文件,返回一个列表

y=[f for f in os.listdir(r'.\\')  if f.endswith(('.py','.txt'))]            # r 表示后面的字符不转义

print(y)                               # 将当前目录下后缀为pytxt的所有文件增加到列表中,并输出

运行结果

root@DESKTOP-4PIP061:/mnt/c/Codes/python# python3 lab8.py
['lab8.py']

8-2  利用os.path创建目录、创建多级目录,判断目录、文件是否存在。

import os

os.mkdir('d:\\test')                                           # 创建一个目录:d:\\test

os.makedirs('d:\\Python\\test')                       # 一次性创建多级目录:d:\\Python\\test

os.path.isdir('d:\\Python\\test')                      # 判断指定的目录是否存在,输出:True、或False 

os.path.isfile(r'd:\\Python\\test\test.txt')       # 判断指定的文件是否存在,输出:True、或False 

os.path.exists(r'd:\\Python\\test\test.txt')      # 判断指定的文件是否存在,输出:True、或False 

os.path.exists(r'd:\\Python\\test')                   # 判断指定的目录是否存在,输出:True、或False 

os.path.join('d:\\python\\test','test.txt')         # 将路径和文件链接:'d:\\python\\test\\test.txt'

运行结果

没有任何输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值