zoukankan      html  css  js  c++  java
  • Python小白入门题一——文件增删改

    题目描述:用python对文件进行增(创建一个文件)、删(删除一个文件)、改(重命名)操作。

    说明:新建了一个文件夹files存放新增的两个文件,随后这两个文件被批量重命名成“数字.txt”,之后这两个文件被删除,存放这两个文件的文件夹也被删除。即开始时是什么样,运行这串代码后还是什么样。

     1 # -*- coding: UTF-8 -*-
     2 import os
     3 path = r"C:Users11476DocumentsPython Scripts"
     4 dir_name = r"files"
     5 os.mkdir(dir_name)
     6 new_path = r"C:Users11476DocumentsPython Scriptsfiles"
     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!")
  • 相关阅读:
    今年要读的书
    java多线程
    json-lib 使用教程
    tomcat原理
    静态long类型常量serialVersionUID的作用
    使用junit4测试Spring
    MySQL各版本的区别
    spring mvc 下载安装
    hibernate、struts、spring mvc的作用
    【面试】hibernate n+1问题
  • 原文地址:https://www.cnblogs.com/MilkoSilver/p/11747424.html
Copyright © 2011-2022 走看看