Jas*_*ers 2 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
Run Code Online (Sandbox Code Playgroud)
另外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)
Run Code Online (Sandbox Code Playgroud)
有关您的第二个问题,请参阅如何给Tkinter文件对话框重点.
注意: 以上示例部分基于Alex Thornton 删除的答案.