Python中删除文件的程序代码
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'))表示屏幕暂停。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

This article discusses the DDoS attack detection method. Although no direct application case of "DebianSniffer" was found, the following methods can be used for DDoS attack detection: Effective DDoS attack detection technology: Detection based on traffic analysis: identifying DDoS attacks by monitoring abnormal patterns of network traffic, such as sudden traffic growth, surge in connections on specific ports, etc. This can be achieved using a variety of tools, including but not limited to professional network monitoring systems and custom scripts. For example, Python scripts combined with pyshark and colorama libraries can monitor network traffic in real time and issue alerts. Detection based on statistical analysis: By analyzing statistical characteristics of network traffic, such as data

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta
