import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
filedir = filedialog.askopenfilename()
print(filedir)
items = open(filedir, 'a+')
text = items.read()
print(text)
When I run the code and select a file, it doesn't output anything. Putting the file location manually in the code still outputs nothing, and the .txt file definitely has content.
The mode in which you are trying to open the file is not valid that's why U are unable to read the file. Try using r+ mode to open, read and write (if already exists) the file.
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
filedir = filedialog.askopenfilename()
print(filedir)
items = open(filedir, 'r+')
text = items.read()
print(text)
Related
I have a python tkinter code which will accept a file path using askdirectory(). The result is like this : C:/Users/gfgf/gas.
I need to pass it into pandas read_excel. But in pandas read_excel I give path as :frame = pd.read_excel(r'C:\Users\gfgf\gas\doj.xlsx').
So how can I convert C:/Users/gfgf/gas into C:\\Users\\gfgf\\gas\\doj.xlsx
try this,
import tkinter
from tkinter.filedialog import askopenfilename
root=tkinter.Tk()
def browse():
file=askopenfilename(filetypes=[("Excel files","*.xlsx")])
print(file)
button1=tkinter.Button(root,text='Browse',command=browse)
button1.pack()
root.mainloop()
print(file) will have the full path with filename
you can read it using pd.read_excel(file) by making file as global
I have some excel files and I want to open them at the same time and print their content. How can I do that with using tkFileDialog ?
Example of how to open many (text) files and print them:
from tkinter import *
from tkinter import filedialog
root = Tk()
root.geometry('300x150')
root.title('Filemenu test')
file_list = filedialog.askopenfilenames()
for file in file_list:
with open(file) as input_file:
text = input_file.read()
print(text)
The Open file dialog will allow you to select from the file list with SHIFT and CTRL.
To open and parse Excel files I recommend you have a look at Pandas.
I'm new to python!
I'm trying to write a code in python (version = 3.5) to scan through MULTIPLE folders, find a specific file, open in read mode, copy the data into another master file on the desktop.
In other words, I have 10 folders, each folder has 3 files which are of the same name. I have to open one file and copy the contents into another file and move on to the next folder to find the same file again, copy the contents and append into the master file.
I am successfully able to scan multiple folders, files and print them but opening in read mode and copy to master file is the problem.
I have created a simple UI to browse to a particular location. This can be seen in the code below.
Here is my code:
import tkinter
from tkinter import filedialog
from tkinter import Button
from tkinter import Scrollbar
import os
from os import path
import sys
import time
import subprocess
from tkinter import messagebox
from tkinter import font
Application = tkinter.Tk()
Application.title("Stride_Activity_Merger")
Application.configure(bg = "CadetBlue3")
Application.geometry("950x650+300+300")
def browse():
browse.filename = filedialog.askdirectory(initialdir=[("All files", "*")])
x = 0
for root, subdirs, files in os.walk(browse.filename):
print('--\nroot_%d = ' %x + root)
x+=1;
list_file_path = os.path.join(root, 'my-directory-list.txt')
for filename in files:
file_path = os.path.join(root, filename)
print('\t- file %s (full path: %s)' % (filename, file_path))
if filename == 'Activity-Table.csv':
with open('Results_For_Activity-Table.txt', 'w+') as output, open('Activity-Table.csv', 'r') as input:
while True:
data = input.read(10)
if data == '': # end of file reached
break
output.write(data)
print("File Found!")
B1 = Button(text = "B r o w s e T o I n p u t F o l d e r", font="None", height=8, width=85, bg="light coral", command=browse)
B1.place(x=85, y=260)
scrollbar = Scrollbar(Application)
Application.mainloop()
Get the file path after
if filename == 'Activity-Table.csv':
use
with open('Results_For_Activity-Table.txt', 'a') as output
this will let you append data to your results file. Use
all_input_data = input.read()
this will read all the data in the input file no need for the while loop
what I want to do is to select multiple files
using the tkinter filedialog
and then add those items to a list.
After that I want to use the list to process
each file one by one.
#replace.py
import string
def main():
#import tkFileDialog
#import re
#ff = tkFileDialog.askopenfilenames()
#filez = re.findall('{(.*?)}', ff)
import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
Now, I am able to select multiple files,
but I dont know how to add those filenames to the list.
any ideas?
askopenfilenames returns a string instead of a list, that problem is still open in the issue tracker, and the best solution so far is to use splitlist:
import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root, title='Choose a file')
print root.tk.splitlist(filez)
Python 3 update:
tkFileDialog has been renamed, and now askopenfilenames directly returns a tuple:
import tkinter as tk
import tkinter.filedialog as fd
root = tk.Tk()
filez = fd.askopenfilenames(parent=root, title='Choose a file')
askopenfilenames
returns a tuple of strings, not a string.
Simply store the the output of askopenfilenames into filez (as you've done) and pass it to the python's list method to get a list.
filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
lst = list(filez)
>>> type(lst)
<type 'list'>
Putting together parts from above solution along with few lines to error proof the code for tkinter file selection dialog box (as I also described here).
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
files = filedialog.askopenfilename(multiple=True)
%gui tk
var = root.tk.splitlist(files)
filePaths = []
for f in var:
filePaths.append(f)
filePaths
Returns a list of the paths of the files. Can be stripped to show only the actual file name for further use by using the following code:
fileNames = []
for path in filePaths:
name = path[46:].strip()
name2 = name[:-5].strip()
fileNames.append(name2)
fileNames
where the integers (46) and (-5) can be altered depending on the file path.
In Python 3, the way it worked for me was this (respect lowercase):
from tkinter.filedialog import askopenfilenames
filenames = askopenfilenames(title = "Open 'xls' or 'xlsx' file")
for filename in filenames:
# print or do whatever you want
I hope you find it useful!
Regards!
I am creating a GUI with a browse button which I only want to return the path. I've been looking at solutions using code like below.
Tkinter.Button(subframe, text = "Browse", command = self.loadtemplate, width = 10).pack()
def loadtemplate(self):
filename = tkFileDialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
if filename:
try:
self.settings["template"].set(filename)
except:
tkMessageBox.showerror("Open Source File", "Failed to read file \n'%s'"%filename)
However I know Tkinter has a built in askopenfilename which is a super easy one line of code for opening files. Is there some way to modify this to return the directory instead of a file? Is there a smaller option than the larger chunk of code I posted?
It appears that tkFileDialog.askdirectory should work. documentation
This code may be helpful for you.
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
Go with this code
First, select the directory for creating a new file
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
# file_path = filedialog.askopenfilename()
file_path = filedialog.askdirectory()
new_file = input("Name file\n")
open_file = open(f"{file_path}\%s.py" % new_file, 'w')
in my case
i created (ok.py) file in ppppp directory
path is: PS C:\Users\demo\Desktop\ppppp\ok.py