how can i save the file based on file path? - python-3.x

i create browse button and it's show me what i want
this is my code
from PyPDF2 import PdfFileReader
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
label_list = []
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
label_list[0].config(text=pdf.getNumPages())
label_list[1].config(text=info.author)
label_list[2].config(text=info.creator)
label_list[3].config(text=info.producer)
label_list[4].config(text=info.subject)
label_list[5].config(text=info.title)
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
browsebutton = tk.Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = tk.Label(root)
pathlabel.pack()
for i in range(6):
label_list.append(tk.Label(root, text=""))
label_list[i].pack()
root.mainloop()
and how can i save or move to new dir from file path browse button?
I really hope for your help

Sounds like you want to have the browse window open starting in a different directory location than where your python script is (the default behavior)?
If so, give the directory name as the parameter to filedialog.askopenfilename() like so:
# Example Directories
# example_path = os.path.abspath('C:/Users/MyName/Desktop')
# example_path = os.path.abspath('C:/example/cwd/mydir/')
# or
example_path = os.path.abspath('C:/Windows/Temp')
filename = filedialog.askopenfilename(initialdir=example_path)
will open the file browser in that directory.

Related

How can i get data from file path using tkinter and PdFileReader

I use this method :
from PyPDF2 import PdfFileReader
from tkinter import *
from tkinter import filedialog
import os
root = Tk()
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
browsebutton = Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = Label(root)
pathlabel.pack()
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
print(info)
author = info.author
creator = info.creator
producer = info.producer
subject = info.subject
title = info.title
if __name__ == '__main__':
path = pathlabel.pack()
get_info(path)
mainloop()
However, i get the following error:
TypeError: invalid file: None
How can i get the file from pathlabel?
Is it possible to open the file from file path?
I see a couple problems here.
Delete this:
if __name__ == '__main__':
path = pathlabel.pack()
get_info(path)
what this is doing is making path = to the result of pathlabel.pack(). That result will always be None as pack() is always going to return None. Then you are passing None to the get_info() function.
Instead lets call get_info from your brousefunc() functions.
Change brousefunc() to this:
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
This will update your label and then also send the correct file path to the get_info function.
If you still wish to use the label's text for the file path you can do path = pathlabel["text"] as this will assign the value of the text to the path.
I can't test PyPDF2 on my end but the below should work for you.
from PyPDF2 import PdfFileReader
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
author = info.author
creator = info.creator
producer = info.producer
subject = info.subject
title = info.title
print(number_of_pages, author, creator, producer, subject, title)
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
browsebutton = tk.Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = tk.Label(root)
pathlabel.pack()
root.mainloop()
To address your question in the comments here is an example that displays in the GUI.
from PyPDF2 import PdfFileReader
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
label_list = []
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
label_list[0].config(text=pdf.getNumPages())
label_list[1].config(text=info.author)
label_list[2].config(text=info.creator)
label_list[3].config(text=info.producer)
label_list[4].config(text=info.subject)
label_list[5].config(text=info.title)
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
browsebutton = tk.Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = tk.Label(root)
pathlabel.pack()
for i in range(6):
label_list.append(tk.Label(root, text=""))
label_list[i].pack()
root.mainloop()

Open a file with a button then storing the path in Python3

As the title states, I want to open a file with a browse button then store the file path for later use. I have no issue browsing the file, I just can't get the path to store into a variable. Many thanks.
from tkinter import *
from tkinter import filedialog
import openpyxl
from termcolor import cprint
# initializing tk
root = Tk()
root.title("Tools")
root.geometry("600x300")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack(side = BOTTOM )
def getFile():
# open dialog box to select file
root.filename = filedialog.askopenfilename(initialdir="/", title="Select file")
#create button
browsebutton = Button(frame, text="Browse", command=getFile)
browsebutton.pack(side = BOTTOM)
#store the open file path into a variable
path = root.filename
You can use global(you should avoid global if possible) or use a class
def getfile():
path.set(filedialog.askopenfilename(initialdir="/", title="Select file")
def do_other_work_with_path():
#your Code here
print(path.get())
path = StringVar()
#using global
def getfile():
global path
path = filedialog.askopenfilename(initialdir="/", title="Select file")
# or using a class for your whole gui
from tkinter import *
from tkinter import filedialog
root = Tk()
class GUI:
def __init__(self, parent):
self.parent=parent
self.button=Button(self.parent, text='Browse', command=self.getfile)
self.button.pack()
def getfile(self):
self.path=filedialog.askopenfilename(initialdir="/", title="Select file")
gui=GUI(root)
#you can also call gui.path with a class
root.mainloop()

Tkinter "Open" Window

I want to replicate the "Open" button (For example on notepad to open a txt file) but I want to have it as a button beside entry in a tkinter window so I could either enter a directory or use button to select a specific folder.
import glob
import os
from tkinter import *
import tkinter.messagebox
for file in os.listdir(r"C:\directory"):
print(file)
root = Tk()
root.resizable(width=FALSE, height=FALSE)
def inital():
pass
#Making Widgets
frameT = Frame(root)
frameT.pack(side=TOP)
frameB = Frame(root)
frameB.pack(side=BOTTOM)
labelstart = Label(frameT, text="Configure")
labelstart.grid()
dirlabel = Label(frameT, text="Directory:")
dirlabel.grid(row=1)
dirinput = Entry(frameT)
dirinput.grid(row=2)
root.mainloop()
How about this :
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
def askopenfile():
# If you want to browse files.
path_to_file = tkFileDialog.askopenfilename() # for a file
# If you want to browse directories.
path_to_folder = tkFileDialog.askdirectory() # for a directory
print "File: " + path_to_file
print "Folder: " + path_to_folder
root = Tk()
b = Button(root, text="CLICK ME", command=askopenfile)
b.pack()
root.mainloop()
Hopefully this will help you, Yahli.

Using Tkinter and suprocess.call

I would like to use tkinter to open a window that will allow a user to select two separate files that will be manipulated several times within my script. I am having trouble finding a way to set the file that will be selected using the button in my tkinter window as a variable so that it can be used within subprocess.call. I have found invoke() but it doesn't seem to have any affect. Any ideas on what I might do would be greatly appreciated.
import os
import sys
import gdal
from gdalconst import *
import numpy as np
import math
import subprocess
from subprocess import call
import math
import datetime
import shutil
import tkinter
from tkinter import *
from tkinter import filedialog
newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
if not os.path.exists(newpath):
os.makedirs(newpath)
newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
if not os.path.exists(newpath_2):
os.makedirs(newpath_2)
newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
if not os.path.exists(newpath_3):
os.makedirs(newpath_3)
if __name__== '__main__':
# Set all of the necessary constants so that the script can create and save the pertinent files
# on the users desktop
#tk1 = Tk()
#tk2 = Tk()
#callTK = 'src_dataset =' + tk1
#callTK_2 = 'srcVH =' + tk2
gdalTranslate = 'C:\Program Files (x86)\GDAL\gdal_translate.exe'
tk1.fileName = filedialog.askopenfilename(text="Open HV File")
tk2.fileName = filedialog.askopenfilename(text="Open VH File")
dst_dataset = os.path.expanduser('~\\Desktop\\Components\\Float32\\newHV32.img')
dstVH = os.path.expanduser('~\\Desktop\\Components\\Float32\\newVH32.img')
sttime = datetime.datetime.now().strftime('(Time_Run = %Y-%d-%m_%H:%M:%S)')
wheel_install_1 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install.py')
wheel_install_2 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install2.py')
ridofz = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\ridofZsv2.py')
to_dB = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\to_dBv2.py')
db_HV = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newHVdB.img')
db_VH = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newVHdB.img')
cmd = "-ot float32 -of HFA" # hopefully this works
# Install necessary packages, which are GDAL and Numpy
# try:
#os.system(wheel_install_1)
#print ("GDAL intalled")
#os.system(wheel_install_2)
#print ("Numpy installed")
#except:
#print ("The packages are't installing properly")
#sys.exit()
# Create three new folders which will house the files that will be created
# along each sequential step of the script
#newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
#if not os.path.exists(newpath):
#os.makedirs(newpath)
#newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
#if not os.path.exists(newpath_2):
#os.makedirs(newpath_2)
#newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
#if not os.path.exists(newpath_3):
#os.makedirs(newpath_3)
root = Tk()
#root.fileName = filedialog.askopenfilename()
root.title("Utilis Sigma Test")
root.iconbitmap(r"C:\Users\jack.UTILIS\Desktop\images\sigma.ico")
root.configure(background="#179EBB")
topFrame = Frame(root)
topFrame.pack()
photo = PhotoImage(file="C:\\Users\\jack.UTILIS\\Desktop\\images\\Utilis_Branding2015_FINAL_Small.gif")
label = Label(root, image=photo)
label.pack(side=RIGHT)
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(root, text="Open HV File", fg="black", command=filedialog.askopenfilename)
button2 = Button(root, text="Open VH FIle", fg="black", command=filedialog.askopenfilename)
button1.pack(side=LEFT)
button2.pack(side=RIGHT)
hvfullCmd = ' '.join([gdalTranslate, cmd, tk1.fileName,dst_dataset])
subprocess.call(hvfullCmd)
vhfullCmd = ' '.join([gdalTranslate,cmd, tk2.fileName,dstVH])
subprocess.call(vhfullCmd)
root.mainloop()
You have to create own function which get filename from askopenfilename and does something with this file. Then you can assign this file to button using command=
import tkinter as tk
from tkinter import filedialog
# --- functions ---
def on_click():
filename = filedialog.askopenfilename()
if filename:
print("Filename:", filename)
else:
print("Filename: not selected")
# --- main ---
root = tk.Tk()
btn = tk.Button(root, text='Click Me', command=on_click)
btn.pack()
root.mainloop()

Loading an audio file using file dialog and playing it with pygame

I'm trying to load a file using the tkinter GUI file dialog and then pass this to another function that will play it using pygame (though I'm open to using another package if it's easier), how would I go about doing this? Below is what a code sample that is representative of what I have so far:
import tkinter, pygame
from tkinter import *
from pygame import *
from tkinter import filedialog
root = Tk()
def open_masker():
global fileName
fileName = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"), ("All Files", "*.*")))
masker_track = fileName
if fileName =="":
fileName = None
else:
fh = open(fileName, "r")
fh.close()
def masker_screen():
global m_screen
m_screen = Toplevel(root)
m_screen.geometry('600x600')
m_screen.transient(root)
m_label = Label(m_screen, text = "Playing New Masker Noise")
m_label.pack(anchor = CENTER)
noise = pygame.mixer.Sound(file = fileName)
noise.play(0, 5000)
noise.stop()
b1 = Button(root, text = 'open file',command = open_masker).pack(anchor=CENTER)
b2 = Button(root, text = 'continue', command = masker_screen).pack(anchor = E)
root.mainloop()
Which just returns the error that pygame couldn't load the file. Is this because it's being loaded in as a string into the fileName variable? If so, how do I change that and access the actual file?
Thanks!
Ok, I have fixed some problems you had, and this is my complete working solution (see the comments in the code for explanations):
import pygame
from tkinter import * # not advisable to import everything with *
from tkinter import filedialog
pygame.mixer.init() # initializing the mixer
root = Tk()
audio_file_name = ''
def open_masker():
global audio_file_name
audio_file_name = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"), ("All Files", "*.*")))
def masker_screen():
# we will also use the audio_file_name global variable
global m_screen, audio_file_name
m_screen = Toplevel(root)
m_screen.geometry('600x600')
m_screen.transient(root)
m_label = Label(m_screen, text = "Playing New Masker Noise")
m_label.pack(anchor = CENTER)
if audio_file_name: # play sound if just not an empty string
noise = pygame.mixer.Sound(audio_file_name)
noise.play(0, 5000)
b1 = Button(root, text = 'open file',command = open_masker)
# does not make sense to call pack directly
# and stored the result in a variable, which would be None
b1.pack(anchor=CENTER)
Button(root, text = 'continue', command = masker_screen).pack(anchor = E)
root.mainloop()
See documentation for more information on how to use correctly the mixer module.

Resources