import os
# 给一个列表,生成文件夹,并在其中新建txt文件,写入文件名内容
# 例如 彭于晏文件夹下有 彭于晏.txt 里面有彭于晏三个字
name_list=["彭于晏","周润发","周杰伦","陈道明","成龙","李连杰","阿里","百度","字节跳动"]
# 批量新建文件夹的关键 for mkdir()
for name in name_list:
os.mkdir(name) # makedirs() 通用
file_name = name + ".txt" # 周杰伦.txt
path = name + "/" + file_name # 周杰伦/周杰伦.txt
# open()方法参数 文件路径 打开方式 w-write
with open(path, "w", encoding="utf-8") as f: # gbk unicode
f.write(name)
#####################
path='测试'
if not os.path.exists(path):
os.mkdir(path)
path_list = []
for dir_name in name_list:
path_name=os.path.join(path,dir_name) # 测试/彭于晏
if not os.path.exists(path_name):
os.mkdir(path_name)
path_list.append(path_name)
for path in path_list:
name=path.split('\\')[空格] # 拼接的斜杠
file_name=name+".txt" # 文件路径 彭于晏.txt
file_path=os.path.join(path,file_name) # 测试/彭于晏/彭于晏.txt
with open(file_path,"w",encoding="utf-8") as f:
f.write(name)
###############################
def creat_dir(path):
"""
创建文件 path一个文件夹名字 返回路径列表
:param path:
:return:
"""
if not os.path.exists(path):
os.mkdir(path)
path_list = []
for dir_name in name_list:
path_name=os.path.join(path,dir_name) # 测试/彭于晏
if not os.path.exists(path_name):
os.mkdir(path_name)
path_list.append(path_name)
return path_list
def create_file(path_list):
"""
创建文件 路径列表 无返回值
:return:
"""
for path in path_list:
name=path.split('\\')[1] # 拼接的斜杠
file_name=name+".txt" # 文件路径 彭于晏.txt
file_path=os.path.join(path,file_name) # 测试/彭于晏/彭于晏.txt
with open(file_path,"w",encoding="utf-8") as f:
f.write(name)
# path_list = creat_dir("测试3")
# create_file(path_list)
##############################
import shutil # 模块提供了一系列对文件和文件集合的高阶操作。 特别是提供了一些支持文件拷贝和删除的函数
os.chdir(r"D:\PycharmProjects\auto_office\class6\测试3\周杰伦")
shutil.copyfile("周杰伦.txt", "周杰.txt") # 复制文件
os.chdir(r"D:\PycharmProjects\auto_office\class6\测试3")
shutil.copytree("周杰伦", "周杰") # 复制文件夹
################################
os.chdir(r"D:\PycharmProjects\auto_office\class6\测试3\周杰")
os.walk("./") # 遍历 寻找当前文件夹下的所有文件或文件夹
for path,dirs,files in os.walk("./"):
print("当前路径",path)#当前路径
print("文件夹列表",dirs)#文件夹列表
print("文件列表",files)#文件列表
########################################
#listdir 列出当前文件夹下的所有文件和文件夹(子文件)列表
all_list=os.listdir("./") # 上面有重定向
print(all_list)
os.rename("周杰.txt","周杰2.txt") # 也可以改文件夹名字,路径改为上一层
os .remove("周杰2.txt") # 删除文件
os.rmdir("空格") # 删除空文件夹 非空会报错
shutil.rmtree("周杰")
class6_os_demo2
最新推荐文章于 2024-07-12 16:16:27 发布