search
HomeBackend DevelopmentPython TutorialPython中删除文件的程序代码

Python是一种面向对象的解释性的计算机程序设计语言,也是一种功能强大而完善的通用型语言,已经具有十多年的发展历史,成熟且稳定。Python 具有脚本语言中最丰富和强大的类库,足以支持绝大多数日常应用。它具有简单、易学、免费、开源、可移植性、解释性、面向对象、可扩展性、可嵌入性以及丰富的库等特性,目前的应用范围也非常广泛,如系统编程、图像处理、数据库编程等方面。
Python开发者可以使用文本编辑器(如Windows的记事本等)或者专业的IDE(集成开发环境)来编写程序代码。IDE使得开发者可以很方便地创建、运行、调试Python程序。IDE可以在Python的官方网站(http://www.python.org)下载,目前(2009年9月)最新版本为Python 3.1.1,本文中将以Python 2.6.2为开发平台进行介绍。
关于Python程序的运行,其实一个Python程序就相当于一个应用程序,它不需要经过编译,只需要用户电脑上面安装Python环境即可。要运行一个py程序,直接双击这个py文件即可。一般情况下,没有提示用户输入或控制屏幕显示,打开一个py文件时会突然闪一下马上就退出,这是由于程序运行已经完成了。若需要显示,则要添加一个屏幕暂停的代码:
os.system('pause')
在使用这个代码前,需要引用os模块:import os
下面开始介绍删除文件的Python程序设计:
很多软件在运行时会自动创建一些备份文件,在程序退出后又不自动删除备份文件,随着文件数量的增加,每隔一段时间就要清理一下。如果文件数量比较多,手工清理显然比较麻烦。于是可以编写一个Python脚本来完成该任务。如下代码:

代码如下:


# -*- coding: cp936 -*-
#file:E01.py
import os
#该函数用于删除文件
def scan(arg, dirname, names):
for file in names:
if file[0]=="~" or file[-4:]==".bak":
print "删除文件:", file
file=dirname+"\\"+file
os.remove(file)
print "完成!"
#提示用户输入目录路径
path=raw_input("请输入要删除文件所在目录:(如D:\\temp)")
if os.path.exists(path)==False: #检查用户输入的目录是否存在,如果不存在则退出程序
print "输入的目录不存在!"
os._exit(1)
os.path.walk(path, scan, 0)
os.system('pause')


运行该程序,它将删除用户指定目录下的以波浪符号(~)开头或以后缀(.bak)结尾的文件。运行结果如下图所示:
下面来分析这段代码。首先,系统操作都在os模型中,所有首先需要导入os模型。然后提示用户输入文件目录,同时检查用户输入的文件目录是否正确。检验目录是否存在使用os.path.exists(path)方法,如果返回True则表示目录存在,如果返回False则表示不存在,则退出程序。退出Python程序采用os._exit(1)方法。os.path.walk()方法是访问目录中的每个目录以及文件,在该方法内调用函数scan。函数scan的参数指定为3个,其中names表示目录内所有文件的名称,为列表类型。然后对于每一个文件检查其文件名是否符合要删除文件名的特征(以波浪符号(~)开头或以后缀(.bak)结尾的文件),如果符合要求,则采用os.remove(file)方法删除。在此值得注意的是,采用os.remove(file)方法删除文件,要求参数file为全路径和文件名,如D:\temp\1.bak。
如果要删除tmp临时文件,只需要将上段代码中的“file[-4:]==".bak"”更改为“file[-4:]==".tmp"”即可。最后一句(os.system('pause'))表示屏幕暂停。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.