python - 将 f.write 文件保存到与找到的 Askopenfilename 相同的目录中

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

最佳答案

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

相关文章:

python - 在 python 中使用正则表达式匹配任何字符和/或未定义的换行符

java - ENOSPC - 多次写入已删除的文件

Node.js Visual Studio 2013 - 路径太长错误

svg - 每个路径上的填充颜色存在问题//SVG CSS 动画//Atom 中的代码与 CodePen 中的代码之间的错误//SVG CSS 动画

regex - 正则表达式精确匹配不带参数的 URL 的最后一个路径段,除非路径以尾部斜杠结尾

Python Django 媒体 url 在设置 DEBUG = True 后不起作用

python - 如何将 python 列表转换为具有预定义列的 pandas 数据框

c++ 11 - 使用目录

无法从C中的txt文件中读取所有数字

python - 在 django admin 中按自定义列表显示字段列表过滤器