Answers for "how to delete a text file in python"

38

python delete file

import os
import shutil

if os.path.exists("demofile.txt"):
  os.remove("demofile.txt") # one file at a time

os.rmdir("test_directory") # removes empty directory
shutil.rmtree("test_directory") # removes not empty directory and its content
Posted by: Guest on August-19-2020
36

python os remove file

import os
os.remove("filename.txt")
Posted by: Guest on February-11-2020
2

python delete text in text file

# Delete all text in a text file
f = open("text_file.txt", "r+")
f.truncate(0)
f.close()
Posted by: Guest on April-30-2021
0

deleting in a text file in python

#get list of lines.
a_file = open("sample.txt", "r") 
lines = a_file. readlines()
a_file. close()
#remove line from list
del lines[1] delete lines.
#write new contents into file
new_file = open("sample.txt", "w+") write to file without line.
for line in lines:
new_file. write(line)
new_file. close()
Posted by: Guest on June-17-2021

Code answers related to "how to delete a text file in python"

Python Answers by Framework

Browse Popular Code Answers by Language