Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

python - Issue sorting files in a folder "ValueError: invalid literal for int() with base 10: ''

I am trying to read and sort the file names of a folder "frames", but I′m getting the error. My code is as follows:

col_frames = os.listdir(path + 'frames/')

# sort file names
col_frames.sort(key=lambda f: int(re.sub('D', '', f)))

# empty list to store the frames
col_images=[]

for i in col_frames:
    # read the frames
    img = cv2.imread(path + 'frames/'+i)
    # append the frames to the list
    col_images.append(img)

And I′m getting this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-6300f903ade1> in <module>
      6 
      7 # sort file names
----> 8 col_frames.sort(key=lambda f: int(re.sub('D', '', f)))
      9 
     10 # empty list to store the frames

<ipython-input-17-6300f903ade1> in <lambda>(f)
      6 
      7 # sort file names
----> 8 col_frames.sort(key=lambda f: int(re.sub('D', '', f)))
      9 
     10 # empty list to store the frames

ValueError: invalid literal for int() with base 10: ''

I do net to convert that to integers. Can you explain me what′s going on and if there is a way around?

While printing print(col_frames) I get this: ['348.png', '1186.png', '412.png', '374.png', '360.png', '406.png', '1192.png', '1179.png', '1145.png', '1623.png', '1637.png', '1151.png', '638.png', '176.png', '88.png', '610.png', '1384.png', '1390.png', '604.png', '162.png', '189.png', '837.png', '77.png', '823.png', '63.png', '1409.png', '1421.png', '1347.png', '1353.png', '1435.png', '980.png', '758.png', '994.png', '1596.png', '764.png', '770.png', '1582.png', '1569.png', '943.png',....]

question from:https://stackoverflow.com/questions/65861512/issue-sorting-files-in-a-folder-valueerror-invalid-literal-for-int-with-base

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Somewhere in your list of files there is at least one filename which does not contain a number. To fix this, either remove these files, or rename them to contain a number, or add following to your code before the line that produces the error:

for filename in col_frames:
    if not any(char.isdigit() for char in filename): # check if there is any number in the filename
        col_frames.pop(filename) # else remove it from the file list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...