2

I am running this script in Python to find a certain line in a file. askopenfilename will ask what file I want to search and the f.write will save the results into a file. How do I automatically save this file in the same place I found the original file?

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

Also askopenfilename opens behind the other windows, how do I make it open on top?

anon582847382
  • 19,907
  • 5
  • 54
  • 57
Jason Rogers
  • 667
  • 1
  • 6
  • 19
  • 1
    You left the parentheses off of `f.close`, which makes that a no-op. You can leave it out entirely because the context manager closes it for you (`with open ...`). It might make most sense to move the file open outside of the loop so you are not repeatedly opening and closing the file. – Steven Rumbalski Apr 11 '14 at 15:45

1 Answers1

5

To extract the directory from a path use os.path.dirname(path).

I would rewrite your code as:

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)

For your second question see How to give Tkinter file dialog focus.

Note: Above example partially based on Alex Thornton's deleted answer.

Community
  • 1
  • 1
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119