将phone_number转换为整数时出错:基数为10的int()的文字无效:''

问题描述 投票:0回答:1

我正在尝试执行以下操作: 该脚本从文件中取出一行,将其拆分,然后应将电话号码设置为星号拨号方案的变量。

文件行看起来像:

Doe,John,Adam,123456789

但是我收到错误:

Error converting phone_number to integer: invalid literal for int() with base 10: ''

同时,据我了解,变量已设置,因为如果我打印它,它就存在。

phone: 123456789

请告诉我,错误是什么?

with open(file_path, 'r') as file:
    i = 0  
    for line in file:
        
        parts = line.strip().split(',')

        # Ensure that there are enough parts in the line
        if len(parts) >= 4:
            surname, name, lastname, phone_number = parts[:4]

            # Check if phone_number is not empty before conversion
            if phone_number.strip():  # Check if the stripped value is not empty
                try:
                    phone_number = int(phone_number)
                    agi.set_variable('PHONE_NUMBER', f"{phone_number}")
                except ValueError as e:
                    print(f"Error converting phone_number to integer: {e}")
                except Exception as e:
                    print(f"Error setting PHONE_NUMBER: {e}")
            else:
                print(f"Empty phone_number encountered on line {i + 1}, skipping...")
        else:
            print(f"Invalid line format on line {i + 1}: {line.strip()}")

        print(f"phone: {phone_number}")
python variables agi
1个回答
0
投票

正如我从您的错误消息中看到的,该空字符串被传递给您的 int() 函数。

再次检查您的文件和代码。

© www.soinside.com 2019 - 2024. All rights reserved.