将 "Can only concatenate str (not "int") 添加到从文件读取的值时获取 str"
Getting "Can only concatenate str (not "int") to str" when adding to a value read from a file
我希望 bots.txt 被读作 int 而不是 str。但是 none 我在互联网上找到的视频有帮助,或者详细介绍了我如何解决这个问题。
这是我的代码
import time
import os
import random
os.system('mode 88,30')
with open('B://JakraG2//.Bots//bots.txt', 'r') as f:
aaa = f.read()
counter = aaa
while True:
time.sleep(0.05)
print("Added 1 to bots.txt")
counter = counter + 1
lel = "{}".format(counter)
with open('B://JakraG2//.Bots//bots.txt', 'w') as f:
f.write("{}".format(lel))
这里是错误
Traceback (most recent call last):
File "loader.py", line 16, in <module>
counter = counter + 1
TypeError: can only concatenate str (not "int") to str
bots.txt
0
当你用f.read读取一个文件时,获取的信息被确定为一个字符串,这就是为什么当你尝试将计数器加1时(f.e 5 + 1),程序认为你正在尝试做这样的事情 "5" + 1.
一个简单的解决方法是声明您从文件中读取的内容是一个整数:
aaa = int(float(f.read()))
读取时的文件始终是字符串 - 您需要转换为整数才能使用整数加法。
import time
# read file
try:
with open('bots.txt', 'r') as f: # you use B://JakraG2//.Bots//bots.txt'
aaa = f.read().strip()
counter = int(aaa)
except Exception as e:
print(e) # for informational purposes when testing
counter = 0 # f.e. file not exists or invalid text2number in it
while True:
time.sleep(0.05)
print("Added 1 to bots.txt")
counter = counter + 1
# overwrites existing file
with open('bots.txt', 'w') as f: # you use B://JakraG2//.Bots//bots.txt'
f.write(f"{counter}")
我希望 bots.txt 被读作 int 而不是 str。但是 none 我在互联网上找到的视频有帮助,或者详细介绍了我如何解决这个问题。
这是我的代码
import time
import os
import random
os.system('mode 88,30')
with open('B://JakraG2//.Bots//bots.txt', 'r') as f:
aaa = f.read()
counter = aaa
while True:
time.sleep(0.05)
print("Added 1 to bots.txt")
counter = counter + 1
lel = "{}".format(counter)
with open('B://JakraG2//.Bots//bots.txt', 'w') as f:
f.write("{}".format(lel))
这里是错误
Traceback (most recent call last):
File "loader.py", line 16, in <module>
counter = counter + 1
TypeError: can only concatenate str (not "int") to str
bots.txt
0
当你用f.read读取一个文件时,获取的信息被确定为一个字符串,这就是为什么当你尝试将计数器加1时(f.e 5 + 1),程序认为你正在尝试做这样的事情 "5" + 1.
一个简单的解决方法是声明您从文件中读取的内容是一个整数:
aaa = int(float(f.read()))
读取时的文件始终是字符串 - 您需要转换为整数才能使用整数加法。
import time
# read file
try:
with open('bots.txt', 'r') as f: # you use B://JakraG2//.Bots//bots.txt'
aaa = f.read().strip()
counter = int(aaa)
except Exception as e:
print(e) # for informational purposes when testing
counter = 0 # f.e. file not exists or invalid text2number in it
while True:
time.sleep(0.05)
print("Added 1 to bots.txt")
counter = counter + 1
# overwrites existing file
with open('bots.txt', 'w') as f: # you use B://JakraG2//.Bots//bots.txt'
f.write(f"{counter}")