Delete Folder Contents and multiple files in Python

hello

How can I delete the contents of a local folder and multiple files in Python?

The current project is for Linux.

i would like delete the extention *.pyc and files name sommefilestmp.flv and files on folder log

i use os with os.remove just this line delete 1 files and i want to delete multiple files in one line

ty
aeko satoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MerijnBSr. Software EngineerCommented:
why multiple files with one line, why not write a function which does this (and which you optionally call recursively for sub dirs)?
0
aikimarkCommented:
Are you processing a single directory or a tree (dir and sub-dirs)?
0
gelonidaCommented:
I don't really understand your question, it is a little fuzzy for me.

if you want to delete one file:
os.remove(fname)

Open in new window

If you want to delete a directory and ALL it's files/subdirs, then use shutil.rmtree:
( https://docs.python.org/2/library/shutil.html )
import shutil
shutil.rmtree(directory_name)

Open in new window


If you want to delete multiple files you need more than one line:
filenames = [ 'file1.txt', 'file2.txt' ]
for filename in filenames:
    os.remove(filename)


if you want to find files matching a glob  (e.g. *.pyc, see also https://en.wikipedia.org/wiki/Glob_%28programming%29 and https://docs.python.org/2/library/glob.html )
then you can do:
import glob
filenames = glob.glob('*.pyc')
for filename in filenames:
    os.remove(filename)

Open in new window


Here a small helper function, that iterates recursively through a directory and returns tuples of (directory, filename)
import os
def file_find(basedir):
    for bdir, dirs, files in os.walk(basedir):
        for fname in files:
            yield (bdir, fname)

Open in new window


If you want to delete all files matching a regular expression, then you could use above function  and the module re ( https://docs.python.org/2/library/re.html )
import re
rex = re.compile('test.*\.pyc$')
for dirname, fname in file_find(basedir):
    if rex.match(fname):
        os.remove(os.path.join(dirname, fname))

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

aikimarkCommented:
You can feed the output of glob() or iglob() into os.remove()
Example:
os.remove(glob.glob('c:\users\aikimark\downloads\Python\*.pyc'))

Open in new window

0
gelonidaCommented:
@aikimark:
my python version does not allow to pass a list to os.remove(), and glob.glob() returns a list. perhaps python 3 allows this?

d:\work>python
Python 2.7.4 (default, Apr  6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, glob, sys
>>> glob.glob('*.xxx')
['f1.xxx', 'f2.xxx', 'f3.xxx']
>>> os.remove(glob.glob('*.xxx'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be string, not list

Open in new window



if you really wanted to write a oneliner you could do:
map(os.remove, glob.glob('*.xxx'))

Open in new window

0
aeko satoAuthor Commented:
ty it works :)
0
aikimarkCommented:
that is why I included iglob(), since it returns an iterable
0
gelonidaCommented:
@aikimark

iglob doesn't work either:
$ python -c "import os; import glob; os.remove(glob.iglob('*.xxx'))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, generator found

Open in new window


python 3.2.3 doesn't seem to handle this either.
$ python3
Python 3.2.3 (default, Feb 27 2014, 21:31:18) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os; import glob; os.remove(glob.iglob('*.xxx'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'generator' object to str implicitly
>>> import os; import glob; os.remove(glob.glob('*.xxx'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'list' object to str implicitly

Open in new window


Perhaps this is a feature just working with very
0
aikimarkCommented:
well, dang. :-(
0
aikimarkCommented:
Did you try a comprehension syntax?
[os.remove(x) for x in glob.glob("*.xxx")]

Open in new window

0
gelonidaCommented:
@aikimark

your most recent suggestion works of course as you pass just one value per call to os.remove()
On the other hand it's not shorter than my previously suggested
map(os.remove, glob.glob('*.xxx'))

Open in new window


Your and my one-linerare a little weird because the create an intermediate list of None values just to have it destroyed afterwards.

Both are only one line shorter than the explicit for loop of my initial answer.
for filename in filenames:
    os.remove(filename)

Open in new window


I'm not sure it's really worth a list comprehension or a map() call
0
aikimarkCommented:
@gelonida

I agree with your analysis.  I only posted my post-closure comments to help future readers and to confirm that my earlier comment wasn't too 'crazy'.   I'm still learning Python, so it still takes me a bit longer than it should to arrive at an answer.  Thanks for your participation.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.