2

Is there a way to SAVE the value of a variable (say an integer) in python? My problem involves calling (entering and exiting) multiple times the same python script (python file, not python function) which in the end creates a txt file. I'd like to name the txt files depending on the number of times the python code was called: txt1.txt,..., txt100.txt for example.

EDIT: The question is not related with the SAVE parameter in fortran. My mistake.

4

3 回答 3

7

并不真地。您可以做的最好的事情是使用全局变量:

counter = 0
def count():
    global counter
    counter += 1
    print counter

绕过对全局语句的需求的替代方法是:

from itertools import count
counter = count()
def my_function():
    print next(counter) 

甚至:

from itertools import count
def my_function(_counter=count()):
    print next(_counter)

最终版本利用了函数是第一类对象的事实,并且可以随时添加属性:

def my_function():
    my_function.counter += 1
    print my_function.counter

my_function.counter = 0 #initialize.  I suppose you could think of this as your `data counter /0/ statement.

但是,看起来您实际上想要将计数保存在文件或其他内容中。这也不是太难。您只需要选择一个文件名:

def count():
    try:
        with open('count_data') as fin:
            i = int(count_data.read())
    except IOError:
        i = 0
    i += 1
    print i
    with open('count_data','w') as fout:
        fout.write(str(i))
于 2013-05-02T15:59:52.540 回答
5

注意:我假设您的意思是:

多次调用(进入和退出)相同的python代码

是您想多次调用整个 Python 脚本,在这种情况下,您需要以 Python 解释器外部的某种方式序列化您的计数器,以使其下次可用。如果您只是询问在一个 Python 会话中多次调用相同的函数或方法,您可以通过多种方式执行此操作,我会向您指出mgilson 的答案

有很多方法可以序列化事物,但您的实现与语言没有任何关系。您想将其存储在数据库中吗?将值写入文件?或者仅从上下文中检索适当的值就足够了吗?例如,此代码每次调用时都会根据output_dir. 这显然很粗糙,但你明白了:

import os

def get_next_filename(output_dir):
    '''Gets the next numeric filename in a sequence.

    All files in the output directory must have the same name format,
    e.g. "txt1.txt".
    '''

    n = 0
    for f in os.listdir(output_dir):
        n = max(n, int(get_num_part(os.path.splitext(f)[0])))
    return 'txt%s.txt' % (n + 1)

def get_num_part(s):
    '''Get the numeric part of a string of the form "abc123".

    Quick and dirty implementation without using regex.'''

    for i in xrange(len(s)):
        if s[i:].isdigit():
            return s[i:]
    return ''

或者,当然,您可以在 Python 脚本旁边写一个类似runnum.cfg某处的文件,并将您当前的运行编号写入其中,然后在代码启动时读取该文件。

于 2013-05-02T16:10:19.367 回答
1

mgilson 的回答为原始问题提供了很好的选择。另一种方法是重构代码,将选择文件名的关注点与计算+保存分开。这是一个代码草图:

for i in ...:
   filename = 'txt%d.txt' % (i,)
   do_something_then_save_results(..., filename)

如果您需要在很多地方执行此操作并希望减少代码重复,那么生成器函数可能会很有用:

def generate_filenames(pattern, num):
   for i in xrange(num):
       yield pattern % (i,)

...
for filename in generate_filenames('txt%d.txt', ...):
   do_something_then_save_results(..., filename)

将“...”替换为您的应用程序中有意义的任何内容。

于 2013-05-02T16:14:13.923 回答