【发布时间】:2013-04-24 10:34:23
【问题描述】:
我想将 2 个 Python 脚本合并为 1 个脚本,因为这样运行起来会更容易。最简单的方法是什么?
脚本 1:打开一个文本文件并将所需的字符串写入输出文件。
#!/usr/bin/env python
with open("mylist.txt") as f:
with open("output1.txt", "w") as f1:
for line in f:
if "[Running] groups/" in line or "[FAILED!] groups/" in line:
f1.write(line)
脚本 2:打开脚本 1 保存的文本文件,并用其他内容替换 2 个字符串并保存输出。
infile = "output1.txt"
outfile = "output2.txt"
delete_list = ["[Running]", "[FAILED!]"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "link_to_path")
fout.write(line)
fin.close()
fout.close()
所以脚本应该读取文本文件,只复制需要的字符串,然后用不同的字符串替换它们并保存在一个文本文件中。
【问题讨论】:
-
复制粘贴成二合一?或者将所有代码移动到函数中,并将两个脚本导入第三个脚本。究竟是什么问题?
-
我想知道如何将它们组合成 1 个脚本,因为这样会更高效、更简洁。
-
with open("mylist.txt") as f, open("output1.txt", "w") as f1:应该会为您省去很多麻烦:P
标签: python list text-files