在执行多个函数之前执行同一文件检查的一种更有效的方法



我认为这很简单,但我没有看到。我想检查文件是否存在;如果是,我会把它读到列表中,但如果不是,我会创建它。示例:

filename = "a_file_name"
filepath = os.path.join(os.getcwd(), filename)
if not os.path.exists(filepath): 
foo() #do some stuff then create file
with open(filename, 'w') as f:
for item in a_list:
f.write(f"{item}n")
else:
#if the file already exists read it into a list
a_list = [line.rstrip() for line in open(filepath)]

这很好,问题是我必须多次这样做(但文件名/路径不同(,所以foo((周围的代码相同,bar((的代码相同等等。我以为装饰器会在这里工作,但问题是,如果文件确实存在,并且装饰器只返回函数,我必须返回列表。。因此,寻求另一种选择,让这件事比多次重复自己更有说服力。

您可以创建文件名函数对的元组列表,然后遍历这些对。

要将早期函数的返回值传播到后一个函数,可以向每个函数调用传递一个dict,并将返回值保存到dict,函数对象是后一个功能检索它的密钥:

def foo(result):
return 1
def bar(result):
return 2 + result[foo] # returns 3 in this example
file_checks = [
('a_file_name', foo),
('b_file_name', bar)
]
result = {}
for filename, func in file_checks:
filepath = os.path.join(os.getcwd(), filename)

if not os.path.exists(filepath): 
result[func] = func(result)
with open(filepath, 'w') as f:
for item in a_list:
f.write(f"{item}n")
else:
a_list = [line.rstrip() for line in open(filepath)]

相关内容

最新更新