Home>Article>Backend Development> How to delete txt files in python

How to delete txt files in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼 Original
2019-06-13 15:48:38 12805browse

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

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')

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')

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

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')

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!

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