Delete multiple text files in one folder - python

from random import *
import os
def createFile(randomNumber):
with open("FileName{}.txt".format(randomNumber), "w") as f:
f.write("Hello mutha funsta")
def deleteFile():
directory = os.getcwd()
os.chdir(directory)
fileList = [f for f in directory if f.endswith(".txt")]
for f in fileList:
os.remove(f)
print ("All gone!")
fileName = input("What is the name of the file you want to create? ")
contents = input("What are the contents of the file? ")
start = input("Press enter to start the hax. Enter 1 to delete the products. ")
randomNumber = randint(0, 1)
while True:
if start == (""):
for i in range(0):
createFile(randomNumber)
randomNumber = randint(0,9999)
break
elif start == ("1"):
deleteFile()
break
else:
print ("That input was not valid")
Above is code I've made to create as many text files as I specify (currently set to 0). I am currently adding a feature to remove all the text files created, as my folder now has over 200,000 text files. However, it doesn't work, it runs through without any errors but doesn't actually delete any of the files.

that is very wrong:
def deleteFile():
directory = os.getcwd()
os.chdir(directory)
fileList = [f for f in directory if f.endswith(".txt")]
for f in fileList:
os.remove(f)
you change the directory: not recommended unless you want to run a system call, mostly you change it to the current directory: it has no effect.
your list comprehension doesn't scan the directory but a string => f is a character! Since it doesn't end with .txt, your listcomp is empty
To achieve what you want you may just use glob (no need to change the directory and pattern matching is handled automatically):
import glob,os
def deleteFile():
for f in glob.glob("*.txt"):
os.remove(f)
this method is portable (Windows, Linux) and does not issue system calls.

For deleting all the files in the directory with name as FileName{some_thing}.txt, you may use os.system() as:
>>> import os
>>> os.system("rm -rf /path/to/directory/FileName*.txt")

Related

files not deletes when using os module

I tried to make a program which delete all of the empty files ( whose size is zero ). Then, i run the program by dragging the script file in "command prompt" and run it .
However, no empty files had deleted (but i have some of them).
Please help me to find the error in my code.
import os
a = os.listdir('C:\\Python27')
for folder in a :
sizes = os.stat('C:\\Python27')
b = sizes.st_size
s = folder
if b == 0 :
remove('C:\\Python27\s')
You're assigning the values iterator os.listdir returns to folder and yet you aren't using it at all in os.stat or os.remove, but instead you are passing to them fixed values that you don't need.
You should do something like this:
import os
dir = 'C:\\Python27'
for file_name in os.listdir(dir):
file_path = os.path.join(dir, file_name)
if os.stat(file_path).st_size == 0:
os.remove(file_path)
You can delete something like the following code and you need to add some exception handling. I have used a test folder name to demonstrate.
import os
import sys
dir = 'c:/temp/testfolder'
for root, dirs, files in os.walk(dir):
for file in files:
fname = os.path.join(root, file)
try:
if os.path.getsize(fname) == 0:
print("Removing file %s" %(fname))
os.remove(fname)
except:
print("error: unable to remove 0 byte file")
raise

How can I check if only txt file exists in a directory with python?

I have to check in a while loop. I have found the following code it shows the file without while loop.
for file in glob.glob("*.txt"):
print(file)
but it does not work in a while loop if i use the following code
a = os.listdir(my_path)
#print(a)
for file in glob.glob("*.txt"):
print(file)
I am trying to program a watcher type in python with OS module
while True:
f = os.listdir(path)
if len(f) > 0:
for i in os.listdir(path):
if i.endswith('.txt'):
continue
else:
dosomething()
time.sleep(5) #so loop checks files every 5 sec
This way you only use os module, glob's not needed.
use os.listdir to get all files in a folder
len to get total files
list comprehension with sum and str.endswith to get count files ending with ".txt"
Demo:
import os
a = os.listdir(my_path)
if len(a) == sum(1 for i in a if i.endswith(".txt")):
print("All Text")
import os
dr = os.listdir(my_path)
if len(dr) == len(filename for filename, file_extension in a if file_extension == '.txt')):
#do stuff
pass
Well, from what i can understand, what you want is to create a watcher service to provide you if a new file is created.
`
import glob
files = glob.glob("*.txt") # Check first time all the files
while True: # till you exit
_old_files_count = len(files) # Get count of files
files = glob.glob("*.txt")
if len(files) > _old_files_count: # If new file is created.
print(*files[_old_files_count:], sep="\n") # Printing all new files in new line.
`
It will provide you with new files created in that particular directory.
Also, with some tweaks you can also get files which are deleted.
Hope it helps.
For using os, just use below instead of glob line.
import os
files = [file for file in os.listdir() if file.endswith("*.txt")]

I don't think I understand Os.walk fully

I've been trying to build a program for work that deletes unneeded files generated by a software when we export stills.
I was quite happy with how it's working. You just drop a folder that you want and it will delete all the files in that folder. But my boss saw me using it and asked if he could just drop the top directory folder in and it would go into each folder and delete the DRX to save him time of doing it manually for each folder.
This is my current program -
#!/usr/bin/env python3
import os
import sys
import site
import threading
import time
from os import path
from os import listdir
from os.path import isfile, join
while True:
backboot = 'n'
while backboot == 'n':
print ("")
file = (input("Please drag and drop the folder containing DRX files you wish to delete : "))
path = file[:-1]
os.chdir(path)
drx = [x for x in os.listdir() if x.endswith(".drx")]
amount = (str(len(drx)))
print("")
print("")
print("")
print ('I have found ' + amount + ' files with the .drx extension and these will now be deleted')
print("")
print("")
print(*drx,sep='\n')
print("")
print("")
print("")
exts = ('.drx')
for item in drx:
if item.endswith(".drx"):
os.remove(item)
print ('Deleted ' + amount + ' files.')
print('')
What I understand about OS.walk it's generating the trees or folders in a given directory by going up or down the tree. So far, I have the user's input for a path location -
file = (input("Please drag and drop the folder containing DRX files you wish to delete : "))
path = file[:-1]
os.chdir(path
I then scan that directory for DRX files
drx = [x for x in os.listdir() if x.endswith(".drx")]
and turn that into a string as well in order to tell the user how many files I found.
amount = (str(len(drx)))
So, I'm guessing, would I need to implement the OS.walk before or during the DRX scan? Would this be better done whit a function? I'm just trying to wrap my head around OS.walk so any help would be amazing. :)
I guess, I'm quite stuck on how to get OS.walk to read my path variable.
for root, dirs, items in os.walk(path):
root is the absolute path for your path input, dirs and items are lists which contain every dir' and file's relative path to the root inside root.
for root, dirs, items in os.walk(path):
for file in filter(lambda x: x.endswith(".drx"), items):
file_path = os.path.join(root, file)
#do what you like to do

command line arguments using python

I have this code that will let the user choose which file he wants to update by passing an argument in the command line, and then it do some more things but I have not included that here:
import sys
import os
from sys import argv
path = "/home/Desktop/python/test"
files = os.walk( path )
filename = argv[1]
if filename in files:
inputFile = open(filename, 'r')
else:
print "no match found"
sys.exit()
inputFile.close()
When I run the script it keeps giving me "no match found" but im pretty sure the file is there. I cant see what Im doing wrong
os.walk() returns a generator, one that produces tuples with (root, directories, files) values for each iteration.
You can't use that generator to test for a single file, not with a simple in membership test.
You'll also need to re-instate the whole path; you can't just open an unclassified filename without the directory it lives in. Just use a for loop here, and break once you found it. The else suite on a for loop only executes when you did not use break (e.g. the file was not found):
path = "/home/Desktop/python/test"
filename = argv[1]
for root, directories, files in os.walk(path):
if filename in files:
full_path = os.path.join(root, filename)
break
else:
print "no match found"
sys.exit()
with open(full_path) as input_file:
# do something with the file
I added a with statement to handle the lifetime of the file object; once the with block is exited the file is automatically closed for you.
Alternatively, you may use following code snippet.
import os.path
filename = argv[1]
path = "/home/Desktop/python/test/"
if os.path.isfile(path + filename):
inputFile = open(path + filename, "r")
else:
print "File Not Found"

want to find the solution of extensions in python

I am new to python any facing some problem in it.
I want to make a script in python which take two inputs:
1. path to dir
2. file extension to remove
If user type the path and extension to remove then what i want is that the file extension typed by the user save in a list and when the file read by the interpretor it automatically remove the extension file.
Here is the code:
import os
Ext_list = []
path=raw_input('Enter the path for Scanning : ')
while True:
x = raw_input('Enter the extension: ')
if x == ' ':
break
Ext_list.append(x)
for (path, subdirs, filesnames) in os.walk(path):
if filesnames is (x):
os.remove(filesnames)
Use this, of course you have to modify it
glob.glob(os.path.join('.', '*.path*'))
it will output an array of the files with that extention. And then.
input = str(raw_input("Please enter file extention "))
files = glob.glob(os.path.join('.', '*.'+input.))
for File in files:
os.remove(File)

Categories

Resources