将f.write文件保存到与askopenfilename相同的目录中

2024-04-26 21:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件infromimport脚本forifline
1条回答
网友
1楼 · 发布于 2024-04-26 21:23:43

要从路径中提取目录,请使用^{}

我会把你的代码改写为:

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

相关问题 更多 >