我有一個腳本,它接受一組數據,並根據當時所需的內容輸入幾個不同輸出的命令行選項。目前,即使沒有任何內容寫入文件,該文件也可能因爲使用「with」而被創建。下面的簡碼代表了我的觀點。如果使用-a和-b選項調用該程序,則會根據需要生成3個具有正確輸出的文件,但如果不需要a或b,則會創建「a.output」和「b.output」文件沒有任何內容。可以使用python「with」命令來選擇性地寫入文件
import argparse
parser = argparse.ArgumentParser(description="description")
parser.add_argument("-a", "--a", action='store_true', default = False, help = "A type analysis")
parser.add_argument("-b", "--b", action='store_true', default = False, help = "b type analysis")
args = parser.parse_args()
master_dictionary = {}
if args.a:
master_dictionary["A"] = A_Function()
if args.b:
master_dictionary["B"] = B_Function()
master_dictionary["default"] = default_Function()
with open("a.output", "w") as A, open("b.output", "w") as B, open("default.output", "w") as default:
for entry in master_dictionary:
print>>entry, printing_format_function(master_dictionary[entry])
我知道我可能崩潰的打印選項中的條件函數調用後去的,但在實際的腳本事情比較複雜,這是不太理想的把打印的分析塊內。我想要一個專門修改with命令的答案。目標是僅當包含文本時才創建「a.output」和「b.output」文件。
我不認爲你的循環會做你認爲它會。在'master_dictionary'中輸入''''會在字符串「A」和「B」上循環,而不是名稱爲'A'和'B'的文件對象。 – BrenBarn 2014-11-21 19:34:15