Delete files with python through OS shell - python

Im Tyring to Delete all Files in E:.
with wildcard.
E:\test\*.txt
I would ask rather than test the os.walk.
In windows.

The way you would do this is use the glob module:
import glob
import os
for fl in glob.glob("E:\\test\\*.txt"):
#Do what you want with the file
os.remove(fl)

A slightly verbose writing of another method
import os
dir = "E:\\test"
files = os.listdir(dir)
for file in files:
if file.endswith(".txt"):
os.remove(os.path.join(dir,file))
Or
import os
[os.remove(os.path.join("E:\\test",f)) for f in os.listdir("E:\\test") if f.endswith(".txt")]

You could use popen for this as well if you want to do it in fewer lines
from subprocess import Popen
proc = Popen("del E:\test\*.txt",shell=False)

If you want to delete file with more than one extension then define those extensions in tuple like below
import os
def purge(dir):
files = os.listdir(dir)
ext = ('.txt', '.xml', '.json')
for file in files:
if file.endswith(ext):
print("File -> " + os.path.join(dir,file))
os.remove(os.path.join(dir,file))

Related

How to move from one directory to another and delete only '.html' files in python?

I attended an interview and they asked me to write a script to move from one directory to another and delete only the .html files.
Now I tried to do this at first using os.remove() . Following is the code:
def rm_files():
import os
from os import path
folder='J:\\Test\\'
for files in os.listdir(folder):
file_path=path.join(folder,files)
os.remove(file_path)
The problem I am facing here is that I cannot figure out how to delete only .html files in my directory
Then I tried using glob. Following is the code:
def rm_files1():
import os
import glob
files=glob.glob('J:\\Test\\*.html')
for f in files:
os.remove(f)
Using glob I can delete the .html files but still I cannot figure out how to implement the logic of moving from one directory to another.
And along with that can someone please help me figure out how to delete a specific file type using os.remove() ?
Thank you.
Either of these methods should work. For the first way, you could just string.endswith(suffix) like so:
def rm_files():
import os
from os import path
folder='J:\\Test\\'
for files in os.listdir(folder):
file_path=path.join(folder,files)
if file_path.endswith(".html"):
os.remove(file_path)
Or if you prefer glob, moving directories is fairly straightforward: os.chdir(path) like this:
def rm_files1():
import os
os.chdir('J:\\Test')
import glob
files=glob.glob('J:\\Test\\*.html')
for f in files:
os.remove(f)
Though it seems unnecessary since glob is taking an absolute path anyway.
Your problem can be described in the following steps.
move to specific directory. This can be done using os.chdir()
grab list of all *.html files. Use glob.glob('*.html')
remove the files. use os.remove()
Putting it all together:
import os
import glob
import sys
def remove_html_files(path_name):
# move to desired path, if it exists
if os.path.exists(path_name):
os.chdir(path_name)
else:
print('invalid path')
sys.exit(1)
# grab list of all html files in current directory
file_list = glob.glob('*.html')
#delete files
for f in file_list:
os.remove(f)
#output messaage
print('deleted '+ str(len(file_list))+' files in folder' + path_name)
# call the function
remove_html_files(path_name)
To remove all html files in a directory with os.remove() you can do like this using endswith() function
import sys
import os
from os import listdir
directory = "J:\\Test\\"
test = os.listdir( directory )
for item in test:
if item.endswith(".html"):
os.remove( os.path.join( directory, item ) )

Find and rename files using a Python script

I am new to Python coding so here a question. I want to find files that are called "untitled" with any kind of extension, e.g. jpg, indd, psd. Then rename them to the date of the current day.
I have tried the following:
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if file.endswith("untitled.*"):
print(file)
When I run the script, nothing happens.
You might find the glob function more useful in this situation:
import glob
for file in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
print(file)
Your function does not print anything as there are probably no files ending with .* in the name. The glob.glob() function will carry out the file expansion for you.
You can then use this to do your file renaming as follows:
import glob
import os
from datetime import datetime
current_day = datetime.now().strftime("%Y-%m-%d")
for source_name in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
path, fullname = os.path.split(source_name)
basename, ext = os.path.splitext(fullname)
target_name = os.path.join(path, '{}{}'.format(current_day, ext))
os.rename(source_name, target_name)
A Python datetime object can be used to get you a suitable timestamp.
Python string comparator does not support wildcards. You can search for "untitled." anywhere in the text:
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if "untitled." in file:
print(file)
keep in mind that this will include any file that has "untitled." at any location of the file.
try with this approach
import os
directoryPath = '/Users/shirin/Desktop/Artez'
lstDir = os.walk(directoryPath)
for root, dirs, files in lstDir:
for fichero in files:
(filename, extension) = os.path.splitext(fichero)
if filename.find('untitle') != -1: # == 0 if starting with untitle
os.system('mv '+directoryPath+filename+extension+' '+directoryPath+'$(date +"%Y_%m_%d")'+filename+extension)
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if(file.startswith("untitled")):
os.rename(file, datetime.date.today().strftime("%B %d, %Y") + "." + file.split(".")[-1])

How to delete a file by extension in Python?

I was messing around just trying to make a script that deletes items by ".zip" extension.
import sys
import os
from os import listdir
test=os.listdir("/Users/ben/downloads/")
for item in test:
if item.endswith(".zip"):
os.remove(item)
Whenever I run the script I get:
OSError: [Errno 2] No such file or directory: 'cities1000.zip'
cities1000.zip is obviously a file in my downloads folder.
What did I do wrong here? Is the issue that os.remove requires the full path to the file? If this is the issue, than how can I do that in this current script without completely rewriting it.
You can set the path in to a dir_name variable, then use os.path.join for your os.remove.
import os
dir_name = "/Users/ben/downloads/"
test = os.listdir(dir_name)
for item in test:
if item.endswith(".zip"):
os.remove(os.path.join(dir_name, item))
For this operation you need to append the file name on to the file path so the command knows what folder you are looking into.
You can do this correctly and in a portable way in python using the os.path.join command.
For example:
import os
directory = "/Users/ben/downloads/"
test = os.listdir( directory )
for item in test:
if item.endswith(".zip"):
os.remove( os.path.join( directory, item ) )
Alternate approach that avoids join-ing yourself over and over: Use glob module to join once, then let it give you back the paths directly.
import glob
import os
dir = "/Users/ben/downloads/"
for zippath in glob.iglob(os.path.join(dir, '*.zip')):
os.remove(zippath)
I think you could use Pathlib-- a modern way, like the following:
import pathlib
dir = pathlib.Path("/Users/ben/downloads/")
zip_files = dir.glob(dir / "*.zip")
for zf in zip_files:
zf.unlink()
If you want to delete all zip files recursively, just write so:
import pathlib
dir = pathlib.Path("/Users/ben/downloads/")
zip_files = dir.rglob(dir / "*.zip") # recursively
for zf in zip_files:
zf.unlink()
Just leaving my two cents on this issue: if you want to be chic you can use glob or iglob from the glob package, like so:
import glob
import os
files_in_dir = glob.glob('/Users/ben/downloads/*.zip')
# or if you want to be fancy, you can use iglob, which returns an iterator:
files_in_dir = glob.iglob('/Users/ben/downloads/*.zip')
for _file in files_in_dir:
print(_file) # just to be sure, you know how it is...
os.remove(_file)
origfolder = "/Users/ben/downloads/"
test = os.listdir(origfolder)
for item in test:
if item.endswith(".zip"):
os.remove(os.path.join(origfolder, item))
The dirname is not included in the os.listdir output. You have to attach it to reference the file from the list returned by said function.
Prepend the directory to the filename
os.remove("/Users/ben/downloads/" + item)
EDIT: or change the current working directory using os.chdir.

Search files in folder using part of the name and save/copy to different folder using Python

I have 700 files in a single folder. I need to find files that have "h10v03" as part of the name and copy them to a different folder using python.
Heres an example of one of the files: MOD10A1.A2000121.h10v03.005.2007172062725.hdf
I appreciate any help.
Something like this would do the trick.
import os
import shutil
source_dir = "/some/directory/path"
target_dir = "/some/other/directory/path"
part = "h10v03"
files = [file for file in os.listdir(source_dir)
if os.path.isfile(file) and part in file]
for file in files:
shutil.copy2(os.path.join(source_dir, file), target_dir)
Does it need to be python?
A unix shell does that for you quite fine:
cp ./*h10v03* /other/directory/
In python I would suggest you take a look at os.listdir() and shutil.copy()
EDIT:
some untested code:
import os
import shutil
src_dir = "/some/path/"
target_dir = "/some/other/path/"
searchstring = "h10v03"
for f in os.listdir(src_dir):
if searchstring in f and os.path.isfile(os.path.join(src_dir, f)):
shutil.copy2(os.path.join(src_dir, f), target_dir)
print "COPY", f
with the glob module (untested):
import glob
import os
import shutil
for f in glob.glob("/some/path/*2000*h10v03*"):
print f
shutil.copy2(f, os.path.join("/some/target/dir/", os.path.basename(f)))
Firstly, find all the items in that folder with os.listdir. Then you can use the count() method of string to determine if it has your string. Then you can use shutil to copy the file.

Getting short path in python

How do I obtain the short path of a file in Windows using python ?
I am using the following code ,
#!/usr/bin/python
import os
import sys
fileList = []
rootdir = sys.argv[1]
for root, subFolders, files in os.walk(rootdir):
for file in files:
fileList.append(os.path.join(root,file))
for File in fileList:
print File
I guess you are looking for this:
http://docs.activestate.com/activepython/2.5/pywin32/win32api__GetShortPathName_meth.html
Although you will need the win32api module for this.
Also see this link:
http://mail.python.org/pipermail/python-win32/2006-May/004697.html
import win32api
long_file_name='C:\Program Files\I am a file'
short_file_name=win32api.GetShortPathName(long_file_name)

Categories