我要做的是打开一个文件,读取第一行(这是一个数字),在该数字上添加一个,然后用该数字替换第一行。但是,我得到一个字符串索引超出范围错误。我的代码是:
f = open("testfile.txt","r")
line = f.readline()
x = line[1]
x +=1
f = open("testfile.txt","w")
f.write(x)
f.close()
感谢。
答案 0 :(得分:2)
x = int(line[0]) # cast the first character at index 0 to an int, shouldn't be a string