pythonLearner
pythonLearner

Reputation: 59

Menu in python tkinter: save file to a new directory

My python tkinter GUI program is writing a text file after doing some operations. I want to add a an export menu so that user can save this file into usb stick or in another directory. (I know we can do normal copy paste). But I would like to add this export menu. What I am trying to achieve is, When user clicks this export menu, the current directory should open, and the user can choose the file (myData.txt which is already being created and is present inside current directory) and user can now select a new directory and save the myData.txt in the new directory. (it should work in Linux platform as well)

#My gui app creates a text file myData.txt in my current folder when I run the program. 

from tkinter import *
from tkinter import messagebox
import sys

def Export_File():
    #what do i need here???


windows = Tk()
menubar = Menu(windows)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Export", command =Export_File )

filemenu.add_command(label="Exit", command=Exit_File)
menubar.add_cascade(label="File", menu=filemenu)
windows.configure(menu=menubar)


windows.mainloop()

Upvotes: 3

Views: 5668

Answers (3)

politecat314
politecat314

Reputation: 141

First, you need to import 2 more things

import os
from tkinter import filedialog

Next, assign a variable to the directory the user chooses and change to that directory using the os module

def Export_File():
    dir_name = filedialog.askdirectory() # asks user to choose a directory
    os.chdir(dir_name) # changes your current directory

To check your current directory, you can always

curr_directory = os.getcwd()
print(curr_directory)

Upvotes: 3

LukeDev
LukeDev

Reputation: 541

Use askdirectory() in tkinter.filedialog. A normal file dialog window is opened and returns the directory of choice as a string.

from tkinter.filedialog import askdirectory
file = askdirectory(initialdir='/', title='Select File')

You should then be able to use the write function to save it somewhere else:

def Export_File():
    file = open('myData.txt', 'w')
    saveHere = askdirectory(initialdir='/', title='Select File')

    file.write(os.path.join(saveHere, 'myData.txt'))

Upvotes: 1

Song
Song

Reputation: 328

If you do not mind using a unusual module, you can continue reading the solution. To make a copy of the file you use the tempfile module. I will provide the code for the moving the file, and the description of the code.

tempfile.mkstemp(suffix='', prefix='tmp', dir=None, text=False) - creating the new file

Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O_EXCL flag for os.open(). The file is readable and writable only by the creating user ID. If the platform uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by child processes. Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it. If suffix is specified, the file name will end with that suffix, otherwise there will be no suffix. mkstemp() does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix. If prefix is specified, the file name will begin with that prefix; otherwise, a default prefix is used. If dir is specified, the file will be created in that directory; otherwise, a default directory is used. The default directory is chosen from a platform-dependent list, but the user of the application can control the directory location by setting the TMPDIR, TEMP or TMP environment variables. There is thus no guarantee that the generated filename will have any nice properties, such as not requiring quoting when passed to external commands via os.popen(). If text is specified, it indicates whether to open the file in binary mode (the default) or text mode. On some platforms, this makes no difference. mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.

Of course, you will have to insert the file contents in there.

with open(file) as file:
    for line in file:
        new = open(file, 'a')
        new.write(line)

The order you do them is create new file, and add text. You might wonder where I an getting the code and the docs from, so I'm telling you. I got the code and the docs here.

Upvotes: 0

Related Questions