首页 > 编程语言 > 详细

Python小白入门题一——文件增删改

时间:2019-10-27 15:34:48      阅读:95      评论:0      收藏:0      [点我收藏+]

题目描述:用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!")

 

Python小白入门题一——文件增删改

原文:https://www.cnblogs.com/MilkoSilver/p/11747424.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!