我正在 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)
对于你的第二个问题,请参阅 How to give Tkinter file dialog focus .
注意:以上示例部分基于 Alex Thornton 的 deleted answer .
关于python - 将 f.write 文件保存到与找到的 Askopenfilename 相同的目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23016842/