简体   繁体   English

在循环中写入文件只写入一次

[英]Writing to a file in a loop only writes once

I have a python file values.py with the contents我有一个包含内容的 python 文件values.py

a=10

I have another python file execute.py with the contents我有另一个 python 文件execute.py的内容

from test.values import a

def changedata():
    with open("values.py",'r+') as f:
        text = f.read()
        new = a + 10
        text = text.replace(str(a), str(new))
        f.seek(0)
        f.write(text)
        f.truncate()

for i in range(0,4):
    changedata()

When I run the execute.py , ideally the contents of value.py should be a=40 , but it is a=20当我运行execute.py时,理想情况下value.py的内容应该是a=40 ,但它是a=20

I fail to understand, why doesn't python change the contents of value.py on each iteration when run in a loop.我不明白,为什么 python 在循环运行时不会在每次迭代中更改value.py的内容。 Currently, the contents of value.py are only changed once even though it is run a in a loop.目前, value.py的内容仅更改一次,即使它是在循环中运行的。 Can someone explain this behavior and also suggest a way to fix this.有人可以解释这种行为并提出解决此问题的方法。

You only execute from test.values import a once, when the script first starts.您只在脚本首次启动时执行from test.values import a一次。 That executes values.py , which assigns the a variable.执行values.py ,它分配a变量。

Rewriting the file doesn't cause the import to be executed again, so you never reassign a with the new value from the file.重写文件不会导致再次执行import ,因此您永远不会使用文件中的新值重新分配a And even if you re-executed the import statement, it wouldn't be updated, as Python remembers which modules have been imported and doesn't re-import them (see python import multiple times ).即使您重新执行import语句,它也不会更新,因为 Python 会记住已导入哪些模块并且不会重新导入它们(请参阅python 多次导入)。

To keep adding to the value in the file, you'll need to run your whole script repeatedly, not just call changedata() in a loop.要继续添加文件中的值,您需要重复运行整个脚本,而不仅仅是在循环中调用changedata() Or you could have changedata() update the a variable instead of using new .或者您可以让changedata()更新a变量而不是使用new

Although you change the contents of values.py and you expect the value of a to update accordingly it does not happen.尽管您更改了values.py的内容并且您希望a的值相应地更新,但它不会发生。 That's because python is not constantly watching loaded modules to reload them in case they were changed.那是因为 python 不会不断地监视加载的模块以重新加载它们以防它们被更改。 Check this answer out, it's pretty similar to yours: How do I reload a module after changing it?检查这个答案,它与你的非常相似: 更改模块后如何重新加载模块?

To elaborate on Barmar's comment, your problem is that you are not updating the value of a each time through the loop.为了详细说明 Barmar 的评论,您的问题是您没有通过循环每次都更新a的值。 a is always 10 (and would still be 10 even if you reimport it after overwriting the file because, as Barmar noted, Python is smart enough to not reimport what has already been imported). a始终为 10(即使您在覆盖文件后重新导入它,仍然是 10,因为正如 Barmar 所指出的,Python 足够聪明,不会重新导入已经导入的内容)。 To get around this, you need to change the value that you are seeking to overwrite with each iteration.为了解决这个问题,您需要更改每次迭代要覆盖的值。 One simple way to do this would be to pass a variable to the function like so:一种简单的方法是将变量传递给 function,如下所示:

from values import a

def changedata(data):
    with open("values.py",'r+') as f:
        text = f.read()
        new = data + 10
        text = text.replace(str(data), str(new))
        f.seek(0)
        f.write(text)
        f.truncate()
        return new

for i in range(0,4):
    a = changedata(a)

In this code, a is passed as a variable to the function changedata() which then seeks to overwrite the previous value of a in values.py with the new value, a + 10 .在此代码中, a 作为变量传递给 function changedata()然后试图用新值a + 10覆盖values.pya的先前值。 But the function then returns this new value and the line a = changedata(a) overwrites the value of a to the value a + 10 so in the next iteration, changedata() is correctly seeking to overwrite this new value.但是 function 然后返回这个新值,并且a = changedata(a) a值覆盖为a + 10的值,因此在下一次迭代中, changedata()正确地试图覆盖这个新值。 The original value of a would no longer be found in the file values.py since it has been overwritten by a + 10 in the first iteration. a的原始值将不再在文件values.py中找到,因为它在第一次迭代中已被a + 10覆盖。

Here you are:给你:

I use an extra variable tmp.我使用了一个额外的变量 tmp。 I your code the replace method search always for 10 to replace it.我的代码替换方法总是搜索 10 来替换它。 But only the first time find the number 10. All the others times 10 does not exists into values.txt但只有第一次找到数字 10。所有其他乘以 10 不存在于 values.txt

from test.values import a

tmp = a

def changedata():
    global tmp
    with open("values.py",'r+') as f:
        text = f.read()
        print(text) 

        new = tmp + 10
        
        text = text.replace(str(tmp), str(new))
        tmp = new
        
        f.seek(0)
        f.write(text)
        f.truncate()

for i in range(0,4):
    changedata()

or without the usage of a global variable and without import the a:或不使用全局变量且不导入 a:


def changedata():
    with open("values.py",'r+') as f:
        text = f.read()
        print(text) 

        array = text.split("=")

        tmp = int(array[1])
        new = tmp + 10
        
        text = text.replace(str(tmp), str(new))
        
        f.seek(0)
        f.write(text)
        f.truncate()

for i in range(0,4):
    changedata()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM