Opening and reading a file with askopenfilename - python

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()

Related

How to overcome dictionary size limitation? Python3 on windows7

I have a script in python 3.6 what parses a .csv file on windows 7. The initial file is a kind of biological analyzer output. I need to make it more human-readable, so I add the comments based on the data in the initial file. I use dictionaries to keep such comments. The script also has a GUI made with Tkinter library.
Everything worked well before I added some extra keys to the dict_2. Now the script cannot be run via double click anymore. However, it still works if I run the script by Thonny.
Are there any ways to overcome this dictionary size limitation?
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
import sys
import subprocess
import os
import csv
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
def callback():
if askyesno('Verify', 'Close?'):
master.destroy()
else:
showinfo('No', 'Continue')
def make_report():
csv_filename = askopenfilename(initialdir = "/",title = "Chose file",filetypes = (("Report","*.csv"),("all files","*.*")))
txt_filename = asksaveasfilename(initialdir = "/",title = "resulting file*.txt",filetypes = (("txt","*.txt"),("all files","*.*")))
if (str(csv_filename)!= "" ) and str(txt_filename)!= "":
with open (str(csv_filename), 'r', newline='', encoding='utf-16') as tsvin:
tsvin = csv.reader (tsvin, delimiter=';')
with open (str(txt_filename) , 'w') as fileOut:
exlc_list = []
dict_1 = {'x1':'x1a', ...., 'x67':'x67a'}
dict_2 = {'y1':'x1a', ...., 'y216':'y216a'}
.....

writing to SSol.txt was successful, but how can i read SSol.txt?

I am using python 3.6.1. I am self-taught in Python.. I am unable to understand what this error is.
Here is my code:
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import urllib.request as request
def a():
url=("https://rp5.ru/%EC%95%88%EB%8F%99%EC%9D%98_%EB%82%A0%EC%94%A8,_%EA%B2%BD%EB%B6%81")
raw_data = request.urlopen(url).read() #Bytes
text = raw_data.decode("utf-8")
where = text.find('k;">')
start_where = where +4
end_start = where +7
f = open("SSSol.txt", 'w+')
decoded = int(text[start_where:end_start])
k=f.write(str(decoded))
t = str(f.readline())
messagebox.showinfo("hello",t)
ttk.Button(win, text="?", command=a).grid()
enter image description here
No error occurred, but nothing was output.
Problem is that you're reusing the f handle after having written to it.
f = open("SSSol.txt", 'w+')
decoded = int(text[start_where:end_start])
k=f.write(str(decoded))
that part is OK. Now:
t = str(f.readline())
you're reading from the end of the file so t is an empty string. So either:
Do f.seek(0) first to rewind the file
close f and open it again, this time using r mode (read-only). (would be safer anyway)
(that said, I suppose that it's not your real code, as writing + reading the same file in the same method is rather ineffective when you already have the buffer handy)

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()

tkinter - retrieve file name during askopenfile

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()

Python CSV.Writer changing saving path

I would like to have my tkinter program prompt the user to select the path the want to save the file which will be produced by the program.
My code looks like this. At this stage the program only saves to one file (the one I defined to test the program)
What code would I use to have 'test_write.csv' changed to any file the user chooses?
##Writing to .cvs file
with open('test_write.csv', 'w') as fp:
a = csv.writer(fp)
# write row of header names
a.writerow(n)
Thank you
Here's an example using tkFileDialog:
import Tkinter
import tkFileDialog
import csv
formats = [('Comma Separated values', '*.csv'), ]
root = Tkinter.Tk()
file_name = tkFileDialog.asksaveasfilename(parent=root, filetypes=formats, title="Save as...")
if file_name:
with open(file_name, 'w') as fp:
a = csv.writer(fp)
# write row of header names
a.writerow(n)
Use the tkFileDialog module.
Example:
import tkFileDialog
with open(tkFileDialog.asksaveasfilename(), "w") as fp:
...
Solution for python3.xxx
import tkinter
from tkinter.filedialog import asksaveasfilename
with open(asksaveasfilename(), 'w') as fp:

Categories