在python中保存变量值

jpc*_*dre 0 python

有没有办法在python中保存变量的值(比如整数)?我的问题涉及多次调用(进入和退出)相同的python脚本(python文件,而不是python函数),最终创建一个txt文件.我想根据调用python代码的次数命名txt文件:例如txt1.txt,...,txt100.txt.

编辑:该问题与fortran中的SAVE参数无关.我的错.

mgi*_*son 7

并不是的.您可以做的最好是使用全局变量:

counter = 0
def count():
    global counter
    counter += 1
    print counter
Run Code Online (Sandbox Code Playgroud)

绕过全局声明需求的另一种选择是:

from itertools import count
counter = count()
def my_function():
    print next(counter) 
Run Code Online (Sandbox Code Playgroud)

甚至:

from itertools import count
def my_function(_counter=count()):
    print next(_counter)
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

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

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))
Run Code Online (Sandbox Code Playgroud)

  • @jpcgandre:等什么?所以就像fortran拯救你的意思是"什么都没有像Fortran拯救"?Fortran的保存不会序列化. (3认同)
  • @HenryKeiter - 你知道fortran吗?(我确实 - 很好).我相信它很好地回答了这个问题.退出函数时,在python中,一切都消失了.没有"保存". (2认同)
  • @HenryKeiter:你认为问题*到底是什么? (2认同)
  • @HenryKeiter - 这不是fortran中的'save`.`save`在程序的调用之间什么都不做. (2认同)
  • @jpcgandre - 等等.你的意思是`python myscript`给`file1`然后'python myscript`给`file2`等等?因为你不会用fortran的'save`来得到它.你需要澄清你在这里问的是什么...... (2认同)

Hen*_*ter 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 ''
Run Code Online (Sandbox Code Playgroud)

或者当然,您只需编写一个名为runnum.cfgPython脚本旁边某处的文件,然后将当前的运行编号写入其中,然后在代码启动时读取该文件.