FormScreenShot
I am very new to python, and I have created a form that requests information from a user, and Im currently stuck (and clueless on where to start) on creating a functional submit button for the form.
Basically, what I am trying to achieve is when the user enters his output directory and hit submits, it prints to a text file. So for example if he browses through and hits C:/Users/Folder
and hits submit, it will output to a text file saying Output_Dir = "C:/Users/Folder"
I am guessing after I create my submit button, I will have to create a function that it calls that writes to the text file.
UI CODE
self.browse_1 = QPushButton(self.input_files1)
self.browse_1.setObjectName(u"browse_1")
self.browse_1.setGeometry(QRect(100, 100, 75, 23))
main code
##Output Directory Button:
self.ui.browse_1.clicked.connect(self.browsebutton_Function)
## SUBMIT FIELDS INPUT FILES
self.ui.pushButton_4.clicked.connect(self.textFileOutput)
##Output Directory Function:
def browsebutton_Function(self):
file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
if file:
self.ui.lineEdit.setText(str(file))
def textFileOutput(self):
output_DIR = self.ui.lineEdit.text()
with open("Output.txt", "w") as text_file:
print(f" Output Directory = {output_DIR}", file=text_file)
Related
I'm very new to Python and I am making a simple program, which starts off with a menu. One of the options, once selected, will ask the user to enter a username. Once a username is entered, the program will search through a list of text files in that directory (Each user will have their own text file, potentially named after them so that when the username is entered, it finds that user) until it finds the right user, and displays their information in the program.
So the output would be like this
Enter the username: ProPlayer27 (Searching through a list of text files in the same directory for this username)
Result found - Proplayer27 + all of the information from that specific text file
I am really unsure of how to do this, I have tried various methods but with little to no success.
I would really appreciate any help I can get!
I understand that in order for all of the text files to be read in the first place, os.listdir needs to be used, so I am using that as a place to start. I have tried to divide it into 3 steps:
Take the input from the user
Search the text files for the user's input
Once the text file has been found, display it onto the program.
I have little to nothing to show, but I know that multiple text files in a directory can be found like this:
for file in os.listdir("D:\Test"):
if file.endswith(".txt"):
print(os.path.join("Test", file))
The following will do what you want using tkinter.
import tkinter as tk
import os
from pathlib import Path
def find_info():
data = user_input.get() #gets the user input in the entry field
entry.delete(0, tk.END) #delete the input after button pressed
nothing = '' # used ensure nothing happens if the entry is blank
folder = "test data" # name of the folder where the text files exist
connected = os.path.join(folder, data + ".txt") # joins the input for search
record = Path(connected) # used for readability to check its existance
lines_read = [] # empty list to store the data you will read
if data != nothing: # make sure the entry was not left blank
if record.exists(): # checks if the record infact exists
with open(connected, "r") as x: # open and read the text file
for every_line in x.read().split("{}"): # list/string handling
if every_line not in lines_read: # check against empty list
lines_read.append(every_line) # writes the content to the list
result = "".join(lines_read) # format and join
check_label["text"] = result # display resutls on the check_label
root = tk.Tk()
root.geometry("400x200")
root.resizable(False, False)
root.title("Sample Program")
user_input = tk.StringVar()
entry = tk.Entry(root, text=user_input, width=20)
entry.pack()
button = tk.Button(root, text="Find Entry", command=lambda: find_info())
button.pack()
check_label = tk.Label(root, font="Times 12")
check_label.pack()
root.mainloop()
I have created a Entry box:
I have created a text file:
save_file.close()
However the data being entered is not saving to the text file. This is being saved:
Accounts
<bound method Entry.get of <tkinter.Entry object .!entry>><bound method Entry.get of <tkinter.Entry object .!entry2>>
Any idea on how to fix this?
You need to call the get method.
Change
save_file.write(str(username_input_box.get))
to
save_file.write(str(username_input_box.get()))
As you are having trouble, I have written out a very basic version of your program which I have tested and it works. It writes the "Accounts" text to the file and when the button is pressed, it writes the content of the entry field to the file too. If you code still isn't working, perhaps you'll need to post a more complete and executable example of your code
from tkinter import *
def creating_text_file():
save_file = open("Accounts.txt", "a")
title = "Accounts"
line = "\n"
save_file.write(title)
save_file.write(line)
save_file.close()
def apending_to_text_file():
save_file = open("Accounts.txt", "a")
save_file.write(str(username_input_box.get()))
save_file.write("\n")
save_file.close()
root = Tk()
username_input_box = Entry(root, width=30)
username_input_box.grid()
btn = Button(root,text="Press Me",command=apending_to_text_file)
btn.grid()
creating_text_file()
root.mainloop()
As an improvement, I'd use the context managers to open/close your file. They look like this
with open("Accounts.txt", "a") as save_file:
save_file.write("Some random text")
#No need to close the file as the context manager does this for you
I want to upload a file by a file entry and then when I click on "Save" I want to get the path of this selected file.
The next step would be to create either a .txt or a yaml file with this path in it as output.
Could someone help me with this?
win.addFileEntry("InputFile")
def press(button):
if button == "Exit":
win.stop()
if button == "Save":
print(path._getfullpathname(__file__))
print("Saved!")
win.addButtons(["Add", "Remove", "Save", "Load", "Exit"], press)
You just need to ask the FileEntry for its contents:
filename = win.getEntry('InputFile')
I maked a script who need to pars 3D printer log files and export it to .xlsx.
I finished that but now I need to make GUI for that script, I finished almost everything except the one thing. I have function like this
def run(templatefilename):
#LIST OF PRINTER LOG FILES
listOfLogFiles = glob.glob(r"newPrintLogs\*.txt")
for logfile in listOfLogFiles:
#PARSING PRINTER LOG FILE
data = parsPrintingLog(logfile)
#WRITE EXCEL FILE
excelWrite(data, templatefilename)
# MOVE FINISHED FILES
dst = "finishedPrintLogs\\" + logfile.split('\\')[-1]
src = r"" + str(logfile)
shutil.move(src, dst)
consoleLog(src + " " + "successfully finished and moved to" + " " + dst)
# print (src, "successfully finished and moved to", dst)
and from this function I need to export the "# MOVE FINISHED FILES".
Before I've maked GUI I used print for printing where the log is moved, but now I don't know how to print it in GUI textbox, it's not necessary to be a textbox, I only need to show that in my GUI application.
Maybe i misunderstand your question, but from what I gathered you are wanting to dump the contents of your log file to be display in the tkinter GUI.
You could use a ttk ScrolledText widget.
Small minimal example"
textbox = ttk.ScrolledText(parent)
log_contents = open(log_file, "r").read()
textbox.insert("end", log_contents)
If you have some other encoding for your log file you could this for example
in textbox.insert log_contents could be decoded to utf-8 by log_contents.decode("utf-8")
You can then handle scrolling, searching the scrolledtext widget highlight found words etc by additional methods to search your log files contents for example.
I am working on python and biopython right now. I have a file upload form and whatever file is uploaded suppose(abc.fasta) then i want to pass same name in execute (abc.fasta) function parameter and display function parameter (abc.aln). Right now i am changing file name manually, but i want to have it automatically.
Workflow goes like this.
----If submit is not true then display only header and form part
--- if submit is true then call execute() and get file name from form input
--- Then displaying result file name is same as executed file name but only change in extension
My raw code is here -- http://pastebin.com/FPUgZSSe
Any suggestions, changes and algorithm is appreciated
Thanks
You need to read the uploaded file out of the cgi.FieldStorage() and save it onto the server. Ususally a temp directory (/tmp on Linux) is used for this. You should remove these files after processing or on some schedule to clean up the drive.
def main():
import cgi
import cgitb; cgitb.enable()
f1 = cgi.FieldStorage()
if "dfile" in f1:
fileitem = f1["dfile"]
pathtoTmpFile = os.path.join("path/to/temp/directory", fileitem.filename)
fout = file(pathtoTmpFile, 'wb')
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
execute(pathtoTmpFile)
os.remove(pathtoTmpFile)
else:
header()
form()
This modified the execute to take the path to the newly saved file.
cline = ClustalwCommandline("clustalw", infile=pathToFile)
For the result file, you could also stream it back so the user gets a "Save as..." dialog. That might be a little more usable than displaying it in HTML.