Python 如何将文本文件中的数字增加1并将其写回文件?
我试图从txt文件中读取一个数字。然后将其增加1,然后将该数字写入文件,但这只会清空文件Python 如何将文本文件中的数字增加1并将其写回文件?,python,Python,我试图从txt文件中读取一个数字。然后将其增加1,然后将该数字写入文件,但这只会清空文件 with open('BestillingNr.txt', 'r') as f: bestillingNr = int(f.read()) bestillingNr += 1 with open('BestillingNr.txt', 'w') as f2: f2.write(f'{str(bestillingNr)}') 我该如何解决这个问题 代码: 您需要关闭第二个文件。您
with open('BestillingNr.txt', 'r') as f:
bestillingNr = int(f.read())
bestillingNr += 1
with open('BestillingNr.txt', 'w') as f2:
f2.write(f'{str(bestillingNr)}')
我该如何解决这个问题
代码:
您需要关闭第二个文件。您缺少了f2.close结尾的(),因此实际上不会执行close方法 在下面的示例中,我将使用
和
创建一个上下文管理器来自动关闭文件
with open('BestillingNr.txt', 'r') as f:
bestillingNr = int(f.read())
bestillingNr += 1
with open('BestillingNr.txt', 'w') as f2:
f2.write(f'{str(bestillingNr)}')
您需要关闭第二个文件。您缺少了f2.close结尾的(),因此实际上不会执行close方法 在下面的示例中,我将使用
和
创建一个上下文管理器来自动关闭文件
with open('BestillingNr.txt', 'r') as f:
bestillingNr = int(f.read())
bestillingNr += 1
with open('BestillingNr.txt', 'w') as f2:
f2.write(f'{str(bestillingNr)}')
在这行
f2.write(f'{str(bestillingNr)}')
之后,应该添加flush命令f2.flush()
此代码运行良好:
f = open('BestillingNr.txt', 'r')
bestillingNr = int(f.read())
f.close()
bestillingNr += 1
f2 = open('BestillingNr.txt', 'w')
f2.write(f'{str(bestillingNr)}')
f2.flush()
f2.close()
在这行
f2.write(f'{str(bestillingNr)}')
之后,应该添加flush命令f2.flush()
此代码运行良好:
f = open('BestillingNr.txt', 'r')
bestillingNr = int(f.read())
f.close()
bestillingNr += 1
f2 = open('BestillingNr.txt', 'w')
f2.write(f'{str(bestillingNr)}')
f2.flush()
f2.close()
flush
这里没有用,需要刷新的所有内容都将在文件关闭时刷新。另外,请注意,Python中的良好实践是使用上下文管理器,请参见另一个答案的示例。flush
在这里是无用的,所有需要刷新的内容都将在文件关闭时进行。另外,请注意Python中的良好实践是使用上下文管理器,请参见另一个答案的示例。