ValueError: invalid literal for int() with base 10

2019-08-20 11:27发布

问题:

I have been trying to iterate through text files to create some text files with the same name in other directory, but with other values. Here is the code

import numpy as np
import cv2, os
from glob import glob

path_in = 'C:/Users/user/labels'
path_out = 'C:/Users/user/labels_90'

for filename in os.listdir(path_in):
    if filename.endswith('txt'):
        filename_edited = []
        for line in filename:
            numericdata = line.split(' ')
            numbers = []
            for i in numericdata:
                numbers.append(int(i))
            c,x,y = numbers
            edited = [c, y, (19-x)]
            filename_edited.append(edited)
            filename_edited_array = np.array(filename_edited)

            cv2.imwrite(os.path.join(path_out,filename),filename_edited_array)

        continue
    else:
        continue

According to my plan, the code should access each text file, do some math with its each line, then create a text file storing the results of math. When I run the code, it raises

numbers.append(int(i))

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

I tried to look for answers but they do not suit to this situation I think

EDIT: I am providing text file example

0 16 6
-1 6 9
0 11 11
0 17 7
0 7 12
0 12 12
-1 19 4

回答1:

That's because with for line in filename you're not reading the file, you are iterating over the string containing the name of the file.

In order to read or write to a file you have to open it (and possibly to close it at the end of the operations).

The best and the most pythonic way to do it is to use the construct with, which closes it automatically at the end of the operations:

import numpy as np
import cv2, os
from glob import glob

path_in = 'C:/Users/user/labels'
path_out = 'C:/Users/user/labels_90'

for filename in os.listdir(path_in):
    if filename.endswith('txt'):
        filename_edited = []
        # open the file in read mode
        with open(filename, 'r') as f:
            for line in f:
                numericdata = line.split(' ')
                numbers = []
                for i in numericdata:
                    numbers.append(int(i))
            # blah blah...
            # blah blah...