python3_os模块

python 实现创建文件夹和创建日志文件的方法_python_脚本之家 (jb51.net)

1、python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。

得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()

返回指定目录下的所有文件和目录名:os.listdir()

函数用来删除一个文件:os.remove()

删除多个目录:os.removedirs(r“c:\python”)

检验给出的路径是否是一个文件:os.path.isfile()

检验给出的路径是否是一个目录:os.path.isdir()

判断是否是绝对路径:os.path.isabs()

检验给出的路径是否真地存:os.path.exists()

返回一个路径的目录名和文件名:os.path.split()     eg os.path.split('/home/swaroop/byte/code/poem.txt') 结果:('/home/swaroop/byte/code', 'poem.txt')

分离扩展名:os.path.splitext()

获取路径名:os.path.dirname()

获取文件名:os.path.basename()

运行shell命令: os.system()

读取和设置环境变量:os.getenv() 与os.putenv()

给出当前平台使用的行终止符:os.linesep    Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'

指示你正在使用的平台:os.name       对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'

重命名:os.rename(old, new)

创建多级目录:os.makedirs(r“c:\python\test”)

os.makedirs 与os.mkdir的区别, 参数解释,并举例_基督徒Isaac的技术博客_51CTO博客

创建单个目录:os.mkdir(“test”)

创建空文件:os.mknod("test.txt")        

获取文件属性:os.stat(file)

修改文件权限与时间戳:os.chmod(file)

终止当前进程:os.exit()

获取文件大小:os.path.getsize(filename)

获取当前执行脚本的绝对路径:os.path.realpath(file)  (验证发现其实只是将当前绝对路径+file,无论执行路径下是否有file文件)

>>> print(os.system('dir'))
 驱动器 D 中的卷是 新加卷
 卷的序列号是 3091-A460

 D:\ipython\testshell_extension\extensions 的目录

2023/09/27  14:44    <DIR>          .
2023/09/27  14:44    <DIR>          ..
2023/09/27  14:23                20 .gitignore
2023/09/27  14:44    <DIR>          testshell
2023/09/27  14:23             2,042 testshell_extension.py
2023/09/27  14:44    <DIR>          __pycache__
               2 个文件          2,062 字节
               4 个目录 988,401,995,776 可用字节
0
>>> print(os.path.realpath('testshell_extension.py'))
D:\ipython\testshell_extension\extensions\testshell_extension.py
>>> print(os.path.realpath('jodie.py'))
D:\ipython\testshell_extension\extensions\jodie.py    
## 实际执行路径下没有jodie.py文件
>>> print(os.path.dirname(os.path.realpath('testshell_extension.py')))
D:\ipython\testshell_extension\extensions

>>> print(os.getcwd())
D:\ipython\testshell_extension\extensions

 

>>> path = './path/to/file.txt'
>>> real_path = os.path.realpath(path)
>>> print(real_path)
D:\ipython\testshell_extension\extensions\path\to\file.txt

 

 

 

 

复制文件:
shutil.copyfile("oldfile","newfile")       oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile")            oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
复制文件夹:
shutil.copytree("olddir","newdir")        olddir和newdir都只能是目录,且newdir必须不存在
重命名文件(目录)
os.rename("oldname","newname")       文件或目录都是使用这条命令
移动文件(目录)
shutil.move("oldpos","newpos")  
删除文件
os.remove("file")
删除目录
os.rmdir("dir")只能删除空目录
shutil.rmtree("dir")    空目录、有内容的目录都可以删
转换目录
os.chdir("path")   换路径

posted @ 2022-01-25 20:50  小鱼小鱼hi  阅读(100)  评论(0编辑  收藏  举报