将f.write文件保存到找到askopenfilename的同一目录中

时间:2014-04-11 15:32:07

标签: python file path save

我在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在其他窗口后面打开,如何在顶部打开?

1 个答案:

答案 0 :(得分:5)

要从路径中提取目录,请使用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)

关于第二个问题,请参阅How to give Tkinter file dialog focus

注意:以上示例部分基于Alex Thornton的deleted answer