tkinter - retrieve file name during askopenfile - python

I have a text editor made with Python and tkinter.
This is my 'open file' method:
def onOpen(self):
file = askopenfile(filetypes=[("Text files", "*.txt")])
txt = file.read()
self.text.delete("1.0", END)
root.title(file)
self.text.insert(1.0, txt)
file.close()
I would like to set the window title equal to the file name. At the moment I'm using whatever askopenfile return as the file name, but this returns for example:
<_io.TextIOWrapper name='/Users/user/Desktop/file.txt' mode='r' encoding='UTF-8'>
This, of course, isn't very nice. I would like whatever askopenfilename would return. But if I call askopenfile and askopenfilename the user has to use the 'open file' dialog twice.
Is there any way to retrieve the file name without the second dialog?
If not, does anyone a RegEx to filter out the file name. if you're good with RegEx, the nicest file name would of course be just 'file.txt' not '/Users/user/Desktop/file.txt'. Either way it's fine, though.

You are passing the file object so you see the reference to the file object as the title, you can get the name from the file object with name = root.title(file.name).
If you want just the base name use os.path.basename:
import os
name = os.path.basename(file.name)

from tkinter import *
from tkinter import filedialog as fd
from PIL import ImageTk, Image
import os
def openfile():
filepath= fd.askopenfilename()
onlyfilename = os.path.basename(filepath)
mylabel.config(text=onlyfilename)
myscreen=Tk()
filebutton=Button(text='choose your file',command=openfile)
filebutton.grid(row=0,column=2)
mylabel = Label(myscreen, text="You chossen file path will be displayed here")
mylabel.grid(row=1,column=2)
myscreen.mainloop()

Related

I tried to make a QRcode from the user's input file with Python but its not working

Here is my code:
import qrcode
from tkinter import *
from tkinter import filedialog
root=Tk()
def choosefile():
global file
file=filedialog.askopenfile(mode='r',title='Choose a File')
choosefilebutton=Button(root,text='Choose a File',command=choosefile)
choosefilebutton.pack()
def submit():
qr=qrcode.make(file)
qr.save('qrcode.png')
choosefilebutton=Button(root,text='Submit',command=submit)
choosefilebutton.pack()
root.mainloop()
It makes a QR code but when I scan the QR code the result is:
<_io.TextIOWrapper name='/Users/charliezhang/Desktop/hello.png' mode='r' encoding='UTF-8'>
I'm new to Python and don't understand everything too well yet
Can someone please help?
You only get a file path and name data with askopenfile.
Should be something like:
f = open(file.name)
qr = qrcode.make(f.read())
f.close()
In Py 3.8.10, the following works:
def submit():
if file:
qr = qrcode.make(file.read())
qr.save('qrcode.png')
Here, file returned from filedialog.askopenfile() is not a string but a file-like object. So, adding the .read() pulls the data from the file. The filedialog.askopenfilename() method returns a string which is the name of the file.
I also add a check for file, since if the user hits the Cancel button from the Open File dialog, file gets set to None. So doing this check helps prevent another error when the user hits the Submit button afterwards.

Python - Can't get received time of an outlook file

I have an outlook file saved locally. I am using filedialog.askopenfile to ask the user to direct the script to the file, this works fine.
However when I then try to check the receive date of the file I am getting the following error:
com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', "We can't open 'Desktop/emails/email.msg'. It's possible the file is already open, or you don't have permission to open it.\n\nTo check your permissions, right-click the file folder, then click Properties.", None, 0, -2147287038), None)
I think the issue is that I am opening the file when I ask the User to point to the file and then trying to open it again with msg = outlook.OpenSharedItem(dir1) but I don't know how to resolve this.
My Code
from tkinter import *
# import filedialog module
from tkinter import filedialog
from tkinter import ttk
def your_script(dir1):
## Import Libraries
import pandas as pd
import numpy as np
from pandas import DataFrame
import win32com.client as client
import pathlib
import win32com.client
import datetime
from datetime import datetime
from time import strftime
######################################################################################################################
######################################################################################################################
outlook = win32com.client.Dispatch('Outlook.Application').GetNamespace('MAPI')
# Open email
msg = outlook.OpenSharedItem(dir1)
#Get email receive date
dt = msg.ReceivedTime
dt = datetime.strptime('2021-01-16', '%Y-%m-%d')
dt = dt.strftime('%d-%b-%Y')
dt
# Ask User to point to file
dir1 = filedialog.askopenfile(mode="r", initialdir="/", title="select the first file",
filetypes=(("Last quarters email", "*.msg"), ("all files", "*.*")))
your_script(dir1)
As #TheLizzard wrote, you are passing a fileobject to your function, but are expecting a path.
This returns the fileobject
filedialog.askopenfile()
Whereas this returns the path to the file
filedialog.askopenfilename()
your
outlock.OpenSharedItem(dir1)
wants a filepath not a fileobject
The error is STG_E_FILENOTFOUND, whcih means there is no file with the given name. You must pass a string with the fully qualified file name, not an object.

Reading a text document and converting it to a string

I'm trying to make a basic script that reads a specified text document, asks for a string of characters to replace and what to replace it, then saves it:
from tkinter import Tk, filedialog
from tkinter.filedialog import askopenfilename
Tk().withdraw()
def OpenFile():
fileName = askopenfilename(initialdir="C:/Users", filetypes = (("Text File", "*.txt"),("All Files","*.*")), title = "Open a document.")
with open(fileName, 'r') as f:
textFile = f.read()
OpenFile()
print(textFile)
There's an error when running the script and selecting a file
Traceback (most recent call last):
File "C:\Users\****\Documents\Python\Find and Replace\replace.py", line 11, in <module>
print(textFile)
NameError: name 'textFile' is not defined
Game on: find what's different:
from tkinter import Tk, filedialog
from tkinter.filedialog import askopenfilename
Tk().withdraw()
def OpenFile():
fileName = askopenfilename(initialdir="C:/Users", filetypes = (("Text File", "*.txt"),("All Files","*.*")), title = "Open a document.")
with open(fileName, 'r') as f:
textFile = f.read()
return textFile # RETURN THE FILE CONTENT HERE SO IT IS VISIBLE TO THE MAIN FUNCTION
textFile = OpenFile() # GET YOUR OUTPUT HERE SO YOU CAN PRINT IT ON THE NEXT LINE
print(textFile)

Get a file name with tkinter.filedialog.asksaveasfilename to append in it

from an GUI application designed with tkinter, I wish to save some datas in a file in appending mode. To get the file's name I use asksaveasfilename from filedialog module. Here is the code:
from tkinter.filedialog import asksaveasfilename
def save_file():
file_name = asksaveasfilename()
if file_name:
f = open(file_name, 'a')
contents = tab_chrono.text_area.get(1.0, 'end')
f.write(contents)
f.close()
The problem happens when I select in the dialog an existing file, I got a warning that the file will be overwritten. It is not true since I append in the file.
Is there a way to get rid of this warning ? Or do I have to rewrite a askappendfilename myself ? This is missing in filedialog module.
The asksaveasfilename dialog accepts a confirmoverwrite argument to enable or disable the file existence check.
file_name = asksaveasfilename(confirmoverwrite=False)
This can be found in the Tk manual for tk_getSaveFile but doesn't appear to be documented for tkinter. It was introduced in Tk 8.5.11 so is relatively new in Tk terms (released Nov 2011).
Use the option confirmoverwrite to prevent the message, when selecting an existing file.
import tkFileDialog
import time
class Example():
dlg = tkFileDialog.asksaveasfilename(confirmoverwrite=False)
fname = dlg
if fname != '':
try:
f = open(fname, "rw+")
text = f.read()
print text
except:
f = open(fname, "w")
new_text = time.time()
f.write(str(new_text)+'\n')
f.close()
Edit: Note that I am using f.read() to be able to print the existing text.
You may want to remove the f.read() and subsequent print statement and replace them with a f.seek(0,2) which positions the pointer at the end of the existing file.
The other option is as follows using the append option in the file open, which will create the file if it doesn't already exist:
import tkFileDialog
import time
class Example():
dlg = tkFileDialog.asksaveasfilename(confirmoverwrite=False)
fname = dlg
if fname != '':
f = open(fname, "a")
new_text = time.time()
f.write(str(new_text)+'\n')
f.close()

Opening and reading a file with askopenfilename

I have the following code where I'm trying to allow the user to open a text file and once the user has selected it, I would like the code to read it (this isn't a finished block of code, just to show what I'm after).
However, I'm having difficulties either using tkFileDialog.askopenfilename and adding 'mode='rb'' or using the code like below and using read where it produces an error.
Does anyone know how I can arrange to do this as I don't wish to have to type Tkinter.'module' for each item such as Menu and Listbox. Beginner to Tkinter and a bit confused! Thanks for the help!
import sys
from Tkinter import *
import tkFileDialog
from tkFileDialog import askopenfilename # Open dialog box
fen1 = Tk() # Create window
fen1.title("Optimisation") #
menu1 = Menu(fen1)
def open():
filename = askopenfilename(filetypes=[("Text files","*.txt")])
txt = filename.read()
print txt
filename.close()
fen1.mainloop()
Obviously the error I'm getting here is:
AttributeError: 'unicode' object has no attribute 'read'
I don't understand how to use the askopen and also be able to read the file I'm opening.
askopenfilename only returns a file name, what you wanted was askopenfile which accepts a mode parameter and opens the file for you.
The filename in your sample code is just that -- a string indicating the name of the file you wish to open. You need to pass that to the open() method to return a file handle for the name. You can then read from the file handle.
Here's some quick and dirty code to run in the Python interpreter directly. (You can run this in a script, too, but I really like REPL interfaces for quickly trying things out. You may like it as well.)
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Tkinter
>>> from tkFileDialog import askopenfilename
>>> root = Tkinter.Tk() ; root.withdraw()
''
>>> filename = askopenfilename(parent=root)
>>> filename
'/tmp/null.c'
>>> f=open(filename)
>>> f.read()
'#include<stdio.h>\n\nint main()\n{\n for(;NULL;)\n printf("STACK");\n\n return 0;\n}\n\n'
>>> f.close()
>>>
Note especially that there's nothing Tkinter-specific in reading the file -- the dialog box just gives you a filename.
Your error is the name of your function. I simply changed def open() for def open1() and it works.
def open1():
filename = askopenfilename(parent=fen1)
print(filename)
f = open(filename)
txt = f.read()
print txt
f.close()
i think you can read your file like this
import sys
from Tkinter import *
import tkFileDialog
from tkFileDialog import askopenfilename # Open dialog box
fen1 = Tk() # Create window
fen1.title("Optimisation") #
menu1 = Menu(fen1)
def open1():
filename = askopenfilename(filetypes=[("Text files","*.txt")])
text1 = open(filename, r)
read_file = text1.read()
print(read_file)
text1.close()
fen1.mainloop()

Categories