简体   繁体   English

Python。 从列表中删除具有其他扩展名的类似项目

[英]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.问题是:如果有同名的 .mp4 文件,我需要删除 .jpg 文件。

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.问题是replace()实际上可能不会更改任何内容,因此您要删除列表中的每个文件。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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