【问题标题】:Saving f.write file to same directory as the askopenfilename was found将 f.write 文件保存到与发现 askopenfilename 相同的目录
【发布时间】:2014-05-25 20:38:22
【问题描述】:

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

【问题讨论】:

  • 你把f.close的括号去掉了,这使得它成为一个空操作。您可以完全忽略它,因为上下文管理器会为您关闭它 (with open ...)。将文件移到循环之外打开可能最有意义,这样您就不会重复打开和关闭文件。

标签: python file path save


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    相关资源
    最近更新 更多