os模块

os模块是Python内置的与操作系统交互的一个模块。

文件夹与文件相关操作

import os

#递归创建文件
os.makedirs('app/a/b/c') 
#递归删除文件,当这个要删除的目录里面有文件,就停止删除
os.removedirs('app/a/b/c') 

#创建单个目录
os.mkdir('app/a/cc') 
#删除单个文件,如果目录里有东西就报错,不删除
os.rmdir('app/a/cc')

#查看某个目录下的内容 ———— 很常用
l = os.listdir('app/a')
print(l)

# 删除,删除了就不能恢复
os.remove(file_path)
# 修改文件的名字       
os.rename(file_path)

路径相关

'''
必会的:
os.path.join
os.path.basedir
os.path.abspath
os.path.basename
os.path.dirname
os.remove
os.rename
os.listdir
'''

# 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略     
s = os.path.join(r'E:\practice',r'app',r'a')
print(s) #E:\practice\app\a

##获取当前文件的绝对路径 *****
print(os.path.abspath('app')) #E:\practice\app

#返回path的目录。其实就是os.path.split(path)的第一个元素  
print(os.path.dirname(r'E:\practice\app'))
#E:\practice

#返回path最后的文件名。如何path以/或\结尾,那么就会返回空值,即os.path.split(path)的第二个元素。 *****
print(os.path.basename(r'E:\practice\app'))
#app

### 如果path存在,返回True;如果path不存在,返回False 
print(os.path.exists(r'E:\practice\app'))


##将这个文件的绝对路径分成目录与文件,注意加r
print(os.path.split(r'E:\practice\app'))
#('E:\\practice\\old_boy\\day14-模块', 'app')

# 如果path是绝对路径,返回True
print(os.path.isabs(r'E:\practice\app'))

其他

#返回path的大小<br></em> 
#实际上获取的是文件的大小,
# 坑:获取目录大小的时候————
# 一般获取目录大小的时候,将里面所有文件的大小累加!!!
print('目录大小:',os.path.getsize('E:\practice'))
print('文件大小:',os.path.getsize('E:\practice\p'))

## 操作系统相关
print(os.sep) # \
print(repr(os.sep)) # '\\'
# 换行符
print(repr(os.linesep))#'\r\n'
#环境变量的分割
print(repr(os.pathsep)) #';'

###
# print(os.system('dir'))#中文乱码

# 在写程序的时候可以下发操作系统的指令
# 在linux系统上相当于发shell命令  *****
print(os.popen('dir').read())

#获取系统环境变量
# print(os.environ)

# 获取当前工作目录,即当前python脚本工作的目录路径    ***
print(os.getcwd())

# 改变当前脚本工作目录;相当于shell下cd
# 路径切换  少用
os.chdir("E:\practice")

# 返回当前目录: ('.')
# os.curdir
# 获取当前目录的父目录字符串名:('..')
# os.pardir

自己总结了几篇相关的博客

os.walk说明

关于文件路径的生成

Python3 文件的重命名

求文件夹大小与删除文件夹:文件夹中有子文件夹与文件,子文件夹中有文件

rename方法实现文件新内容替换旧内容

将文件file_new_path中的内容替换到file_path中并且不修改file_path的文件名。

最后默认会删掉file_new_path这个文件。

import os


### 测试:file_new_path中存的是新内容,file_path中存的是旧内容,需要把新内容替换到旧内容中,但是文件名还得是file_path的! 
file_path = "/Users/wanghongwei/file.txt"
file_new_path = "/Users/wanghongwei/file_new.txt"

with open(file_path,"r") as f1:
    file_msg = f1.read()


with open(file_new_path,"r") as f2:
    file_new_msg = f2.read()

print("file_msg>>>",file_msg)
"""
file_msg>>> file
file
file
"""
print("file_new_msg>>>",file_new_msg)
"""
file_new_msg>>> file_new
file_new
file_new
"""
# 修改 + 替换 —— 只在mac/linux下可直接用rename
os.rename(file_new_path,file_path)
print("新的file_path的值:",file_path)
"""
新的file_path的值: /Users/wanghongwei/file.txt
"""

### 重新打开file_path中的内容看看:
with open(file_path,"r") as f3:
    file_msg = f3.read()
print("新的file_path中的内容:",file_msg)
# 文件内容被替换了
"""
新的file_path中的内容: file_new
file_new
file_new
"""
##### 最后可以看到,file_new_path这个目录下的文件被系统默认删掉了!!!