简体   繁体   中英

Delete every 1 of 2 or 3 files on a folder with Python

What I'm trying to do is to write a code that will delete a single one of 2 [or 3] files on a folder. I have batch renamed that the file names are incrementing like 0.jpg, 1.jpg, 2.jpg... n.jpg and so on. What I had in mind for the every single of two files scenario was to use something like "if %2 == 0" but couldn't figure out how actually to remove the files from the list object and my folder obviously.

Below is the piece of NON-WORKING code. I guess, it is not working as the file_name is a str.

import os

os.chdir('path_to_my_folder')

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    print(file_name)

    if file_name%2 == 0:
      os.remove();

Yes, that's your problem: you're trying to use an integer function on a string. SImply convert:

if int(file_name)%2 == 0:

... that should fix your current problem.

Your filename is a string, like '0.jpg' , and you can't % 2 a string. 1

What you want to do is pull the number out of the filename, like this:

name, ext = os.path.splitext(filename)
number = int(name)

And now, you can use number % 2 .

(Of course this only works if every file in the directory is named in the format N.jpg , where N is an integer; otherwise you'll get a ValueError .)


1. Actually, you can do that, it just doesn't do what you want. For strings, % means printf-style formatting, so filename % 2 means “find the %d or similar format spec in filename and replace it with a string version of 2 .

Thanks a lot for the answers! I have amended the code and now it looks like this;

import os

os.chdir('path_to_the_folder')

for f in os.listdir():
  name, ext = os.path.splitext(f)
  number = int(name)

if number % 2 == 0:
    os.remove()

It doesn't give an error but it also doesn't remove/delete the files from the folder. What in the end I want to achieve is that every file name which is divisible by two will be removed so only 1.jpg, 3.jpg, 5.jpg and so on will remain.

Thanks so much for your time.

A non-Python method but sharing for future references;

cd path_to_your_folder
mkdir odd; mv *[13579].png odd

also works os OSX. This reverses the file order but that can be re-corrected easily. Still want to manage this within Python though!

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