简体   繁体   中英

How to iterate through a list of file path names and delete each one?

I have a script that creates a list of local files by path name that I would like to see deleted. The essence of my problem in the code below.

If it's easier just to move these files rather than delete them, that's an option. I've seen it might be an option to set the directory before I can get it do delete but I'm hoping for a more efficient function that will just read the paths and deal with them.

I don't need any function to discriminate between any file path names stored in the list. I want each file stored in the list, OUT.

The code as is now gives the error:

TypeError: remove: illegal type for path parameter

Code:

import os

files = ['/users/computer/site/delete/photo1.jpg', '/users/computer/site/delete/photo3.jpg']

os.remove(files)

os.remove() takes a single path as argument, not a list of paths. You have to do something like:

for f in files:
    os.remove(f)

For starters, you are calling os.remove(LIST CALLED files).

You want to iterate through the files and call os.remove on each individual file.

    for file in files:
      os.remove(file)

You can't delete the list at once. You must iterate over all of the files and delete each one. The code for removing files from the list -

import os

files = ['/users/computer/site/delete/photo1.jpg', '/users/computer/site/delete/photo3.jpg']
for f in files:
   os.remove(f)

您可以使用列表理解

[os.remove(f) for f in ['/users/computer/site/delete/photo1.jpg', '/users/computer/site/delete/photo3.jpg']]

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