Home > Backend Development > Python Tutorial > How to delete txt files in python

How to delete txt files in python

爱喝马黛茶的安东尼
Release: 2019-06-20 10:52:23
Original
12914 people have browsed it

How to delete txt files in python

How to delete txt files in python? Let me introduce the basic steps:

If there is a tt text file under the d drive, we To delete it

How to delete txt files in python

First introduce the os module

import os
Copy after login

Related recommendations: "python video tutorial"

Use Use the remove command under os to delete the file. The parameter is r'd:/tt.txt'. Usually the path string is r string

os.remove(r'd:/tt.txt')
Copy after login

Now the changed file has been deleted. Now Let’s run the command again and see if there are any errors.

import os
os.remove(r'd:/tt.txt')
os.remove(r'd:/tt.txt')
Copy after login

This is the error that is prompted. In order to write a more robust program, we usually need to check the file before deleting it. does it exist.

How to delete txt files in python

Use the path.exists command to check whether the file exists. The parameter is still the path string

os.path.exists(r'd:/tt.txt')
False
Copy after login

With the if statement, we can write a robust command to delete files.

if os.path.exists(r'd:/tt.txt'):os.remove(r'd:/tt.txt')
Copy after login

The above is the detailed content of How to delete txt files in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template