Python - 从文件中读取整数并在操作后将其替换到同一文件中
Python - Reading an integer from a file and replacing it on the same file after its manipulation
我正在尝试从文本文件中读取一个数字,将此数字加 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
它不起作用,有人可以帮忙吗!
这段代码应该有效:
# 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))
只是抛出另一个答案,你可以 seek
一个文件位置,前提是你已经在 read/write more ('r+'
)
中打开文件
with open("groupcount", "r+") as f:
groupcount = f.read()
i = int(groupcount)
f.seek(0)
f.write(str(i+1))
注意两个答案在处理文件时都使用 with
。
read
也会选择换行符,所以这只有在只有一个数字的情况下才有效。
如果您想在需要后续数据向前移动的文件中间插入内容,这将不起作用。
我正在尝试从文本文件中读取一个数字,将此数字加 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
它不起作用,有人可以帮忙吗!
这段代码应该有效:
# 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))
只是抛出另一个答案,你可以 seek
一个文件位置,前提是你已经在 read/write more ('r+'
)
with open("groupcount", "r+") as f:
groupcount = f.read()
i = int(groupcount)
f.seek(0)
f.write(str(i+1))
注意两个答案在处理文件时都使用 with
。
read
也会选择换行符,所以这只有在只有一个数字的情况下才有效。
如果您想在需要后续数据向前移动的文件中间插入内容,这将不起作用。