ValueError:int()的无效文字,基数为10:"f" [英] ValueError: invalid literal for int() with base 10: 'f'

查看:121
本文介绍了ValueError:int()的无效文字,基数为10:"f"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试遍历文本文件,以在其他目录中创建具有相同名称但具有其他值的一些文本文件.这是代码

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

我正在提供文本文件示例

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

推荐答案

这是因为使用for line in filename并没有读取文件,而是遍历包含文件名的字符串.

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).

做到这一点的最好也是最Python的方法是使用构造with,该构造会在操作结束时自动将其关闭:

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...

这篇关于ValueError:int()的无效文字,基数为10:"f"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆