python os

本文介绍了使用Python进行文件和目录的基本操作,包括获取当前工作目录、列出目录内容、执行系统命令、检查文件是否存在及是否为文件等。通过具体代码示例展示了如何在不同操作系统上进行这些操作。

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



#encoding:UTF-8
#python OS module

import os
import shutil

print(os.name)
cur_pwd = os.getcwd()
print(cur_pwd)
all_file = os.listdir(cur_pwd)
print(all_file)

fileDir = os.path.abspath('.') + '/ab.txt'
dir = os.path.abspath('.') + '/aa'

#if os.path.exists(fileDir):
 #os.remove('a.txt')

#if os.path.exists(dir):
 #shutil.rmtree(dir) #删除文件夹


os.system('ls') #执行系统命令
os.system('rm aaa -rf') #执行系统命令

print(os.sep)#可以取代操作系统特定的路径分割符,?
print(os.linesep)#给出当前平台使用的行终止符

print(os.path.split(fileDir))#函数返回一个路径的目录名和文件名

print(os.path.isfile(fileDir))#os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。
print(os.path.isdir(dir))

print(os.path.abspath(fileDir))#获得绝对路径
print(os.path.getsize(fileDir))#获得文件大小,如果name是目录返回0L

print(os.path.splitext(fileDir))#分离文件名与扩展名

print(os.path.join(dir,'a.txt'))#连接目录与文件名或目录

print(os.path.basename(fileDir))#返回文件名

print(os.path.dirname(fileDir))#返回文件路径

print('修改成功')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值