我正在尝试从文本文件中读取一个数字,在此数字中加1,然后用python中的新数字覆盖旧数字
file = open('group_count','w+')# opens the text file which contains a number
groupcount = file.read() # reads the number
i = int(groupcount) # supposed to convert the number from the text file to an interger
groupcountnew=groupcount+1 # supposed to 'add one' to that number in the text file
file.write(groupcountnew) # will write that new number to the text file, overriding the original number
它不起作用,请有人帮忙!
答案 0 :(得分:0)
此代码段应该有效:
# opening the source file
with open('group_count.txt','r') as f:
# reading the number
data=f.read()
#calculating the new number
new_data = int(data) + 1
# writing the new number on the same file
with open('group_count.txt','w') as f:
f.write(str(new_data))
答案 1 :(得分:0)
只是为了提出另一个答案,你可以seek
文件位置,只要你以更多的读/写方式打开文件('r+'
)
with open("groupcount", "r+") as f:
groupcount = f.read()
i = int(groupcount)
f.seek(0)
f.write(str(i+1))
请注意,在处理文件时,这两个答案都使用with
。
read
也会获取新的换行符,因此只有在您只有一个数字时才会有效。
如果您想在文件中间插入需要后续数据进行随机播放的内容,则无效。