简体   繁体   中英

Delete Contents of a Special Directory Python (Windows)

I have pretty basic Python knowledge and unfortunately it's so basic that I have no idea how to do what I want to do. I did some searches and I found half the answer to my question.

The plan is to delete the contents of a folder, but the directory differs on system to system due to the username. Let's say the directory is 'C:\\Users\\USER\\Documents\\VideoEditor\\JunkFiles' but with my program I wish for it to attempt to delete the files for all the different versions. Here is an example list: 'C:\\Users\\USER\\Documents\\VideoEditor09\\JunkFiles' 'C:\\Users\\USER\\Documents\\VideoEditor10\\JunkFiles' 'C:\\Users\\USER\\Documents\\VideoEditor11\\JunkFiles'

So basically,

How would I tell it where the directories are no matter what the username? How do I tell it to delete the contents of the directories specified, but keep the folder there (if possible)?

Thanks!

Theo.

What you could try is the following:

import os
user = 'some_user_name'
videoEditors = ['VideoEditor09','VideoEditor10','VideoEditor11']
for i in videoEditors:
    os.chdir('C:\Users\%s\Documents\%s\JunkFiles'%(user,i))
    files = os.listdir('.')
    for file in files:
        os.remove(file)

The main thing I used here was the Python os package and a list of the desired folders to browse. Also the '%s' is part of Python string formatting .

Hope this helps!

You could access the user's documents directory like this:

>>> import os
>>> documents = os.path.join(os.environ['USERPROFILE'], 'Documents')
>>> documents
'C:\\Users\\poke\\Documents'
>>> directories = [os.path.join(documents, 'VideoEditor{0}\\JunkFiles'.format(y)) for y in ('09', '10', '11')]
>>> directories
['C:\\Users\\poke\\Documents\\VideoEditor09\\JunkFiles', 'C:\\Users\\poke\\Documents\\VideoEditor10\\JunkFiles', 'C:\\Users\\poke\\Documents\\VideoEditor11\\JunkFiles']

You can then just loop through the files of the directories to delete them, or if deleting the folders is okay as well (you could create them afterwards again), you could also just use shutil.rmtree :

>>> import shutil
>>> for directory in directories:
        shutil.rmtree(directory)

os.path.expanduser

>>> os.path.expanduser('~')
'C:\\Users\\falsetru'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM