2

I am trying to open a file using 'askopenfilename' and then save the contents of that file to a new file. i could then open that new file for amendment. However I am getting errors and when I attempt to do so. Any help appreciated.

def startapp(self):
    self.grid()

    filebutton = tkinter.Button(self, text="Open File for Selection button", command=self.getfile)
    filebutton.grid(column=1, row=0)

    quitbutton = tkinter.Button(self, text="Quit", command=quit)
    quitbutton.grid(column=2, row=0)

    self.grid_columnconfigure(0, weight=1)

def getfile(self):   #this is the open file function

    selectedfile = filedialog.askopenfilename(filetypes=[('All files', '*.*')])
    temp = tempfile.TemporaryFile()
    temp.write(selectedfile)

The errors provided:

Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:/Users/**/PycharmProjects/FileAnalyser/FileAnalyser1/GUI/ParentWindow.py", line 31, in getfile
temp.write(selectedfile)
File "C:\Python34\lib\tempfile.py", line 399, in func_wrapper
return func(*args, **kwargs)
TypeError: 'str' does not support the buffer interface
peahead99
  • 25
  • 1
  • 4

1 Answers1

1

It looks like you're trying to write text (strings) to this file. If so, you'll need to specify a non-binary mode when creating the TemporaryFile by changing

temp = tempfile.TemporaryFile()

to

temp = tempfile.TemporaryFile(mode='w')

See this answer for more details and the tempfile docs for the fact that it defaults to expecting bytes, not strings.

Community
  • 1
  • 1
myersjustinc
  • 714
  • 1
  • 7
  • 15