简体   繁体   English

在 Python 3.7.3 中将.txt 文件转换为 integer

[英]Convert .txt file to integer in Python 3.7.3

I need to turn a.txt file with a single number into a variable with the type 'int'.我需要将带有单个数字的.txt 文件转换为类型为“int”的变量。 This is my code so far:到目前为止,这是我的代码:

   coinBalance = open.('coinBalance', 'r')

   coinBalance = str(coinBalance)

   coinBalance = int(coinBalance)

And it gives the error: ValueError: invalid literal for int() with base 10: "<_io.TextIOWrapper name='coinBalance' mode='r' encoding='UTF-8'>"它给出了错误: ValueError: invalid literal for int() with base 10: "<_io.TextIOWrapper name='coinBalance' mode='r' encoding='UTF-8'>"

As pointed out by @Moosefeather, you're trying to cast a filepointer to a string and int instead of reading the contents and casting them.正如@Moosefeather 所指出的,您正在尝试将文件指针转换为字符串和int,而不是读取内容并转换它们。 The code below will read the contents of the file 'coinBalance' and then cast that string to an int.下面的代码将读取文件 'coinBalance' 的内容,然后将该字符串转换为 int。

coinBalance = int(open('coinBalance').read())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM