我一直在尝试读取文件,然后用一些更新的数据覆盖它.我试过这样做:
#Created filename.txt with some data
with open('filename.txt', 'r+') as f:
data = f.read()
new_data = process(data) # data is being changed
f.seek(0)
f.write(new_data)
Run Code Online (Sandbox Code Playgroud)
由于某种原因,它不会覆盖文件,并且它的内容保持不变.
我正在尝试使用timeit.timeit来查找执行特定代码行所需的时间.问题是这一行包含变量,我需要以某种方式导入它们,所以我的问题是如何?为了更清楚,代码看起来像这样:
def func():
var1 = 'aaa'
var2 = 'aab'
t1 = timeit.timeit('var1==var2', 'from __main__ import ___', number = 10**4) # here I'm missing what to put after the import
Run Code Online (Sandbox Code Playgroud)
如果我试图在这个代码中执行此代码,__main__我会直接使用'from __main__ import var1, var2'
Any解决方案导入变量吗?
在我读到的关于timeit的所有地方,我发现只能以这种方式使用变量:
s1 = 'abc'
s2 = 'abc'
timeit.timeit('s1==s2', 'from __main__ import s1, s2', number=10**4)
Run Code Online (Sandbox Code Playgroud)
要么
s1 = 'abc'
s2 = 'abc'
def func():
timeit.time('s1==s2', 'from __main__ import s1,s2', number=10**4)
Run Code Online (Sandbox Code Playgroud)
which means that you can also use timeit.timeit in a function as long as the variables are in the main program. I would like to use timeit.timeit with variables that are within the scope it is in, for example:
def func():
s1 = 'abc'
s2 = 'abc'
timeit.timeit(...)
Run Code Online (Sandbox Code Playgroud)
As you …