Python function return is none - python

I have a problem in my project. In my program I have the availability to choose more files if I want. The Problem is, that the return choosen_files has the list of the files but choosen_files which calls the more_files() method is none.
Do you have any suggestion?
Here is my code
import tkinter as tk
from tkinter import filedialog as fd
def get_files(path):
root = tk.Tk()
root.withdraw()
files = fd.askopenfilenames(
parent=root, title='Choose all files you want', initialdir=path)
return list(files)
def more_files(choosen_files, path):
print("choosen files:")
[print(file) for file in choosen_files]
wantMoreFiles = input(
"Do you want to choose more files? [(1) yes, (2) no]").lower()
if wantMoreFiles in ['1', 'y', 'yes']:
new_files = get_files(path)
choosen_files.extend(new_files)
more_files(choosen_files, path)
else:
return choosen_files
#this has the correct list
files = ['path/file1']
path = 'path'
choosen_files = more_files(files, path)
#this is none
Thank you very much!

You don't return anything on the last line.
Just return more_files(files, path)

Related

How to create function to python file of different folder my own code editor?

I am creating an code editor but my code is only run python file which is in same folder where code editor file is also present
and when I open another folder in side bar and select a file from and run it than my terminal shows error
I tried many times but I am unable to fix it
Please tell me how to fix it
error:-
python: can't open file 'D:\\coding notes\\pytho project\\Anmol.py': [Errno 2] No such file or directory
This is my code :-
import os
import subprocess
from tkinter import*
from tkinter import ttk
from tkinter.filedialog import askdirectory, asksaveasfilename
def process_directory(parent,path):
for i in os.listdir(path):
abspath = os.path.join(path,i)
dirv = os.path.isdir(abspath)
oid = tree.insert(parent,END,text=i,open=False)
if dirv:
process_directory(oid,abspath)
def Open(event=None):
global path
for i in tree.get_children():
tree.delete(i)
path = askdirectory()
abspath = os.path.abspath(path)
root_node = tree.insert("",END,text=abspath,open=True)
process_directory(root_node,abspath)
def select_file(event=None):
global file
item = tree.selection()
file = tree.item(item,"text")
abspath = os.path.join(path,file)
editor.delete(1.0,END)
with open(abspath,"r") as f:
editor.insert(1.0,f.read())
def save(event=None):
global file
if file == "":
saveas()
else:
item = tree.selection()
file = tree.item(item,"text")
filepath = os.path.join(path,file)
with open(file,"w") as f:
f.write(editor.get(1.0,END))
root.title(os.path.basename(file) + "-Python")
def saveas(event=None):
global file
file = asksaveasfilename(defaultextension=".py",filetypes=[("Python Files","*.py")])
if file == "":
file = None
else:
with open(file,"w") as f:
f.write(editor.get(1.0,END))
root.title(os.path.basename(file) + "-Python")
def run(event=None):
global file
if file == "":
pass
else:
command = f"python {file}"
run_file = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
Output, error = run_file.communicate()
output.insert(END,f"{file}>>\n")
output.insert(END,Output)
output.insert(END,error)
root = Tk()
tree = ttk.Treeview()
tree.pack(side=LEFT,fill=BOTH)
file = ""
path = ""
editor = Text()
editor.pack(expand=True,fill=BOTH)
output = Text(height=15)
output.pack(expand=True,fill=BOTH)
root.bind("<Control-Alt-o>",Open)
root.bind("<Control-s>",save)
root.bind("<Control-Alt-s>",saveas)
root.bind("<Shift-Return>",run)
tree.bind("<<TreeviewSelect>>",select_file)
root.mainloop()
If the selected file is inside a sub-folder of the selected folder, then the absolute path created by abspath = os.path.join(path,file) inside select_file() is not the correct absolute path (miss the sub-folder information).
One of the way is to save the absolute path in values option when inserting into the treeview:
def process_directory(parent,path):
for i in os.listdir(path):
abspath = os.path.join(path,i)
dirv = os.path.isdir(abspath)
# save the absolute path in "values" option
oid = tree.insert(parent,END,text=i,open=False,values=(abspath,))
if dirv:
process_directory(oid,abspath)
Then inside select_file() you can get the absolute path by getting the values option instead of joining the selected folder and the selected file:
def select_file(event=None):
global file
item = tree.selection()
# get the absolute path
file = tree.item(item,"values")[0]
if os.path.isfile(file):
editor.delete(1.0,END)
with open(file,"r") as f:
editor.insert(1.0,f.read())
Same apply to save() as well.

Mini Search engine Python(File finder and keyword finder)

I'm working on a search engine but I'm facing problems,I want like words from notepad to show on my 'search results', but it's not showing anything, and if you could help me doing like how many times the keyword that I'm searching for got repeated I would appreciate it this is the code:
from tkinter import *
import os
from tkinter.filedialog import askdirectory
from tkinter import messagebox
import subprocess
def content_analyser(pat):
with open(pat,'r') as f:
try:
for line in f:
if search in line:
d.update()
d.insert(END, pat)
break
except:
pass
def smali_finder(pat):
try:
for file in os.listdir(pat):
spat=pat+'/'+file
if os.path.isdir(spat):
smali_finder(spat)
else:
if file.endswith(".smali"):
content_analyser(spat)
except Exception as e:
print ("Error:::",pat,e)
def fing(path):
global search
if search_word.get()=='':
var=messagebox.showwarning(message="Please a search word")
else:
search=search_word.get()
smali_finder(path)
def save_list():
with open("saved_result","w") as sfile:
sfile.write('\n'.join(d.get(0,END)))
var=messagebox.showwarning(message="File names are saved as {}".format("saved_result.txt"))
def chose_folder():
global path
foldername = askdirectory()
path=foldername
folder_name.delete(0,END)
folder_name.update()
folder_name.insert(END, path)
if __name__=="__main__":
parent=Tk()
parent.title('File Finder')
Label(parent,text="Folder name: ").grid(row=0,column=0,sticky='e')
folder_name=Entry(parent,width=20)
folder_name.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=9)
Label(parent,text="Search word: ").grid(row=1,column=0,sticky='e')
search_word=Entry(parent,width=20)
search_word.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=9)
Label(parent,text="Search Results: ").grid(row=3,column=0,sticky='e')
d=Listbox(parent,width=125,height=20)
d.grid(row=4,column=3,padx=2,pady=2,sticky='we',columnspan=9)
Button(parent,text="Folder",command=lambda:chose_folder()).grid(row=0,column=10,sticky='e'+'w',padx=2,pady=2,)
start=Button(parent,text="Start",command=lambda:fing(path)).grid(row=1,column=10,sticky='e'+'w',padx=2,pady=2,)
save=Button(parent,text="Save",command=lambda:save_list())
save.grid(row=2,column=10,sticky='e'+'w',padx=2,pady=2)
Button(parent,text="Exit",command=parent.destroy).grid(row=3,column=10,sticky='e'+'w',padx=2,pady=2)
parent.mainloop()

How to add buttons in python?

I have a code which manages my file transfers. Now I want to add a tkinter to it so I can actually make a button 'run' which will let me run the code. I don't know where to implement the tkinter code as I don't know where to begin.
This is my current code:
import os
source1 = r'D:FolderX'
location2 = 'c:\data\AM\Desktop\destination'
black_list = ['folder1', 'folder2']
for root, dirs, files in os.walk(source1):
#Exclude the blacklist folders.
dirs[:] = [d for d in dirs if d not in black_list]
for file in files:
file_path = os.path.join(root, file)
if os.path.getsize(file_path) == 0:
continue
if file.endswith(".tdms"):
tdms_path = (os.path.join(root, file))
file_size = os.path.getsize(tdms_path)
if file_size == 0:
continue
else:
continue
metadata = td.read_metadata(tdms_path)
print(metadata)
dfs.append(pd.DataFrame([metadata.properties.values()], columns=metadata.properties.keys()))
df = pd.concat(dfs)
df.to_excel(locatie2 + '\\' + 'final_sheet.xlsx'
Here's an example of how to use buttons with tkinter that I think will help.
import tkinter
import tkMessageBox
top = tkinter.Tk()
def buttonPressed():
# put code for what happens when button pressed here
messagebox.showinfo("Window Title", "The code is now running")
B = tkinter.Button(top, text="Press Me", command=buttonPressed)
B.pack()
top.mainloop()
Hope this helps!

Python pass variable values in functions

So this is my full code. All I want is append excel files to one excel by sheets from a specific folder. It's GUI and has 3 buttons browse, append, and quit. How do i get path value from browsed folder(filename) ? thanks
from tkinter import *
from tkinter.filedialog import askdirectory
import tkinter as tk
import glob
import pandas as pd
import xlrd
root = Tk()
def browsefunc():
filename = askdirectory()
pathlabel.config(text=filename)
return filename
def new_window():
all_data = pd.DataFrame()
all_data1 = pd.DataFrame()
path = browsefunc()+"/*.xlsx"
for f in glob.glob(path):
df = pd.read_excel(f,sheetname='Scoring',header=0)
df1 = pd.read_excel(f,sheetname='Sheet1',header=0)
all_data = all_data.append(df,ignore_index=False)
all_data1 = all_data1.append(df1,ignore_index=True)
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
all_data.to_excel(writer, sheet_name='Scoring')
all_data1.to_excel(writer, sheet_name='Sheet1')
writer.save()
browsebutton = Button(root, text="Browse", command=browsefunc).pack()
Button(root, text='Append', command=new_window).pack()
Button(root, text='quit', command=root.destroy).pack()
pathlabel = Label(root)
pathlabel.pack()
mainloop()
It is not entirely clear what you are asking, so can you edit the question to be more specific?
I think you are trying to get the local variable filename (from inside the function browsefunc) able to be accessed outside the function as a global variable. Use return. This tutorial explains it nicely.
At the end of browsefunc you add
return filename
and when you call browsefunc you run
path = browsefunc()
That assigns the variable fdback to whatever you return from browsefunc. It can be an integer, float, string, or list etc.
So, final code is:
def browsefunc():
filename = askdirectory()
pathlabel.config(text=filename)
return filename
def new_window():
path = browsefunc()
I would recommend using more explicit variable and function names.

Running a script for many files of the same extension and writing the results to a text file

I'm trying to write a script to extract data from a number of files in a directory with the extension ".tp6" and then write all of that data to a single text file.
It's able to get data from each file correctly and print them to the terminal, but I haven't been able to 'pass' each data point to another function that writes it to a text file.
Any ideas? Thank you!
import glob
import os
import Tkinter
import tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dir_path = tkFileDialog.askdirectory()
os.chdir(dir_path)
def main():
for file_path in glob.glob('*.tp6'):
uncovext(file_path)
def main2():
for file_path in glob.glob('*.tp6'):
totext(uncovext)
#find and print data from each .tp6 file - this part works correctly
def uncovext(file_path):
for line in open(file_path):
if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
text = line[36:47]
number = float(text) * 10000
print('%.3f' % number)
def totext(uncovext):
with open("output.txt", "a") as f:
f.write(uncovext)
f.close()
if __name__ == '__main__':
main()
main2()
I think it was a matter of naming: if you change your input parameter of totext function to p_uncovext for example, it should work. You need also to call the function to text on your loop.
import glob
import os
import Tkinter
import tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dir_path = tkFileDialog.askdirectory()
os.chdir(dir_path)
def main():
for file_path in glob.glob('*.tp6'):
uncovext(file_path)
#find and print data from each .tp6 file - this part works correctly
def uncovext(file_path):
for line in open(file_path):
if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
text = line[36:47]
number = float(text) * 10000
totext('%.3f' % number)
def totext(p_uncovext):
with open("output.txt", "a") as f:
f.write(p_uncovext)
f.close()
if __name__ == '__main__':
main()
You have a couple of problems. First uncovext doesn't save the data it parses from the input file. After printing to the screen, it is just thrown away. You could collect it into a list and return that for further processing. Then, you call the writer in a second function and you don't have any way for main to let main2 know what the data is.
An easy fix is a single function that calls uncovext and uses its result to call totext.
import glob
import os
import Tkinter
import tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dir_path = tkFileDialog.askdirectory()
os.chdir(dir_path)
def main():
for file_path in glob.glob('*.tp6'):
totext(uncovext(file_path))
#find and print data from each .tp6 file - this part works correctly
def uncovext(file_path):
output = []
for line in open(file_path):
if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
text = line[36:47]
number = float(text) * 10000
output.append('%.3f\n' % number)
return output
def totext(uncovext):
with open("output.txt", "a") as f:
f.writelines(uncovext)
if __name__ == '__main__':
main()
You could also rewrite your parser as a generator and write code that I find more self-explanatory (that's just me though...)
def main():
with open('output.txt', 'a') as f:
for file_path in glob.glob('*.tp6'):
f.writelines(uncovext(file_path))
#find and print data from each .tp6 file - this part works correctly
def uncovext(file_path):
for line in open(file_path):
if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
text = line[36:47]
number = float(text) * 10000
yield '%.3f\n' % number

Categories