Python:向int''joinfilterstr.isdigit,random_file添加定界符 脚本输出

问题描述

因此,我尝试从img_20.png这样的文件名中打印数字,在这种情况下,它将打印20

但是,当文件是.mp4文件时,Python会将img_51.mp4读为514而不是51

是否可以在此脚本中添加定界符.,以便它显示51而不是514

脚本

import os,sys,random

folder_path = "FOLDERPATH"

def upload_photo():
    list = os.listdir(folder_path)
    number_files = len(list)

    for i in range(number_files):
        e = 0
        try:
            random_file = random.choice(os.listdir(folder_path))
            print(random_file)
            print (int(''.join(filter(str.isdigit,random_file))))
            break
        except:
            print("Hit except")

upload_photo()

输出

Matts-MacBook-Pro-5:Reddit matt$ python test.py
img_4.mp4
44
Matts-MacBook-Pro-5:Reddit matt$ python test.py
img_43.mp4
434
Matts-MacBook-Pro-5:Reddit matt$ python test.py
img_33.jpg
33
Matts-MacBook-Pro-5:Reddit matt$ python test.py
img_23.mp4
234
Matts-MacBook-Pro-5:Reddit matt$ python test.py
img_16.jpg
16
Matts-MacBook-Pro-5:Reddit matt$ python test.py
img_36.jpg
36
Matts-MacBook-Pro-5:Reddit matt$ python test.py
img_14.mp4
144

解决方法

(移动评论以回答问题)

您可以使用split方法删除文件扩展名。

尝试一下:

print (int(''.join(filter(str.isdigit,random_file.split('.')[0]))))

如果文件没有扩展名,这也将起作用。