要从路径中提取目录,请使用
我正在Python中运行此脚本,以查找文件中的某一行。askopenfilename
会询问我想搜索哪个文件,f.write会将结果保存到一个文件中。如何将此文件自动保存在原始文件所在的位置?
from tkFileDialog import askopenfilename
filename = askopenfilename()
file = open(filename, "r")
for line in file:
if "INF: Camera timeout" in line:
with open("../timeouts.txt", "a") as f:
f.write(line)
f.close
此外,askopenfilename
在其他窗口后面打开,如何使其在顶部打开?
os.path.dirname(path)
。
我会把你的代码重写为:
from os.path import join, dirname
from tkFileDialog import askopenfilename
infilename= askopenfilename()
outfilename = join(dirname(infilename), 'timeouts.txt')
with open(infilename, 'r') as f_in, open(outfilename, 'a') as f_out:
fout.writelines(line for line in f_in if "INF: Camera timeout" in line)
关于第二个问题,请参阅如何使Tkinter文件对话框聚焦。
注意:以上示例部分基于Alex Thornton删除的答案。