python保存变量值_用python保存变量值

注意:我假设您的意思是:calling (entering and exiting) multiple times the same python code

您希望多次调用整个Python脚本,在这种情况下,您需要在Python解释器外部以某种方式序列化计数器,以便下次可以使用它。如果您只是想在一个Python会话中多次调用同一个函数或方法,那么可以通过多种方式来实现,我将向您指出mgilson's answer。

有很多方法可以序列化,但是您的实现实际上与语言没有任何关系。是否要将其存储在数据库中?将值写入文件?或者仅仅从上下文中检索适当的值就足够了吗?例如,这段代码每次调用时都会根据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的文件,并在其中写入当前的运行号,然后在代码启动时读取它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值