简体   繁体   中英

Python. Remove similar items with other extension from list

I have a problem. After this code working:

path, dirs, files = next(os.walk(f':stories/'))
    print(files)

i have a list, containing different strings:

['2021-07-23_14-52-16_UTC.jpg', '2021-07-23_14-52-16_UTC.mp4',
 '2021-07-23_15-59-38_UTC.jpg', '2021-07-23_15-59-38_UTC.mp4',
 '2021-07-23_17-23-06_UTC.jpg', '2021-07-23_17-23-06_UTC.mp4',
 '2021-07-23_19-42-32_UTC.jpg', '2021-07-23_20-04-18_UTC.jpg',
 '2021-07-23_20-04-18_UTC.mp4', '2021-07-23_20-38-03_UTC.jpg',
 '2021-07-23_20-38-03_UTC.mp4', '2021-07-23_21-38-22_UTC.jpg',
 '2021-07-23_21-38-22_UTC.mp4', '2021-07-23_21-42-07_UTC.jpg',
 '2021-07-23_21-42-07_UTC.mp4', '2021-07-23_21-42-34_UTC.jpg',
 '2021-07-23_21-42-34_UTC.mp4', '2021-07-24_01-01-30_UTC.jpg',
 '2021-07-24_01-01-30_UTC.mp4', '2021-07-24_06-57-14_UTC.jpg',
 '2021-07-24_10-22-46_UTC.jpg', '2021-07-24_12-38-47_UTC.jpg',
 '2021-07-24_13-07-34_UTC.jpg']

Problem is: I need to remove .jpg files, if there is .mp4 file with the same name.

My solution was:

for _ in files:
    temp = _.replace('.mp4', '.jpg')
    if temp in files:
        os.remove(_)

but this part of code removes every file.

Can someone help me or tell, what my mistake is. Thanks.

The problem is that replace() may not actually change anything, so you're removing every file in the list. Try this:

for file in files:
    temp = _.replace('.mp4', '.jpg')
    if temp != file and temp in files:
        os.remove(file)

You can try this

l=['2021-07-23_14-52-16_UTC.jpg', '2021-07-23_14-52-16_UTC.mp4',
 '2021-07-23_15-59-38_UTC.jpg', '2021-07-23_15-59-38_UTC.mp4',
 '2021-07-23_17-23-06_UTC.jpg', '2021-07-23_17-23-06_UTC.mp4',
 '2021-07-23_19-42-32_UTC.jpg', '2021-07-23_20-04-18_UTC.jpg',
 '2021-07-23_20-04-18_UTC.mp4', '2021-07-23_20-38-03_UTC.jpg',
 '2021-07-23_20-38-03_UTC.mp4', '2021-07-23_21-38-22_UTC.jpg',
 '2021-07-23_21-38-22_UTC.mp4', '2021-07-23_21-42-07_UTC.jpg',
 '2021-07-23_21-42-07_UTC.mp4', '2021-07-23_21-42-34_UTC.jpg',
 '2021-07-23_21-42-34_UTC.mp4', '2021-07-24_01-01-30_UTC.jpg',
 '2021-07-24_01-01-30_UTC.mp4', '2021-07-24_06-57-14_UTC.jpg',
 '2021-07-24_10-22-46_UTC.jpg', '2021-07-24_12-38-47_UTC.jpg',
 '2021-07-24_13-07-34_UTC.jpg']
for i in l[:]:
    if i.replace('.jpg','.mp4') in l:
        os.remove(i)
print(l)

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