Python小白入门题一——文件增删改
题目描述:用python对文件进行增(创建一个文件)、删(删除一个文件)、改(重命名)操作。
说明:新建了一个文件夹files存放新增的两个文件,随后这两个文件被批量重命名成“数字.txt”,之后这两个文件被删除,存放这两个文件的文件夹也被删除。即开始时是什么样,运行这串代码后还是什么样。
1 # -*- coding: UTF-8 -*- 2 import os 3 path = r"C:\Users\11476\Documents\Python Scripts" 4 dir_name = r"files" 5 os.mkdir(dir_name) 6 new_path = r"C:\Users\11476\Documents\Python Scripts\files" 7 #add 8 file1_name = "ground.txt" 9 file2_name = "predict.txt" 10 file = open(os.path.join(new_path,file1_name),'w',encoding = 'utf-8') 11 file = open(os.path.join(new_path,file2_name),'w',encoding = 'utf-8') 12 count = 1 13 #rename 14 for file in os.listdir(new_path): 15 if os.path.isfile(os.path.join(new_path,file)) == True: 16 new_name = file.replace(file,"%d.txt"%count) 17 os.rename(os.path.join(new_path,file),os.path.join(new_path,new_name)) 18 count += 1 19 print("Done!") 20 #delete 21 count = 1 22 for file in os.listdir(path): 23 new_name = file.replace(file,"%d.txt"%count) 24 os.remove(os.path.join(new_path,new_name)) 25 count += 1 26 os.rmdir(new_path) 27 print("Finish!")