本文主要是介绍class6_os_demo2,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import os
# 给一个列表,生成文件夹,并在其中新建txt文件,写入文件名内容
# 例如 彭于晏文件夹下有 彭于晏.txt 里面有彭于晏三个字name_list=["彭于晏","周润发","周杰伦","陈道明","成龙","李连杰","阿里","百度","字节跳动"]# 批量新建文件夹的关键 for mkdir()
for name in name_list:os.mkdir(name) # makedirs() 通用file_name = name + ".txt" # 周杰伦.txtpath = name + "/" + file_name # 周杰伦/周杰伦.txt# open()方法参数 文件路径 打开方式 w-writewith open(path, "w", encoding="utf-8") as f: # gbk unicodef.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" # 文件路径 彭于晏.txtfile_path=os.path.join(path,file_name) # 测试/彭于晏/彭于晏.txtwith 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_listdef create_file(path_list):"""创建文件 路径列表 无返回值:return:"""for path in path_list:name=path.split('\\')[1] # 拼接的斜杠file_name=name+".txt" # 文件路径 彭于晏.txtfile_path=os.path.join(path,file_name) # 测试/彭于晏/彭于晏.txtwith 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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!