Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将文本文件中的数字增加1并将其写回文件?_Python - Fatal编程技术网

Python 如何将文本文件中的数字增加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)}') 我该如何解决这个问题 代码: 您需要关闭第二个文件。您

我试图从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)}')
我该如何解决这个问题

代码:


您需要关闭第二个文件。您缺少了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中的良好实践是使用上下文管理器,请参见另一个答案的示例。