Folder access permission denied python [Permission: Errno 13] - python

Hello everyone viewing this question and trying to solve it!
I am making a GUI-based project planner where I need to add oroject name, requirements and steps to achieve which are then saved. I am also adding a feature to add files to it according to relevancy. But when I try to test it I get this: PermissionError: [Errno 13] Permission denied: '<project name>'. I don't know where I am going wrong despite of reading many such question. I have tried chmod but even that is not working. Here is the code:
from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
import os
WIN = Tk()
files =[]
def copy(src,dest):
os.chmod(dest, 0o777)
with open(src,'r') as f, open(dest,'w+') as f2:
f2.write(f)
def start(name):
os.startfile(name)
#<---Button functions--->
def Addfile():
global files
WIN.filename = askopenfilename(initialdir = "C:",title = "choose your file")
print(WIN.filename)
added_fr = Frame(text_box_files)
added_fr.pack()
f_name = Label(added_fr,text=WIN.filename)
f_name.pack()
#dest = shutil.copyfile(WIN.filename, destination)
files.append(WIN.filename)
f_b = Button(added_fr,text="Open",command=lambda x = WIN.filename: start(x))
f_b.pack()
def submit():
global files
name = name_ent.get()
req = text_box.get("1.0",END)
steps = text_box_step.get("1.0",END)
if name != "" and name not in os.listdir() and req != "" and steps != "":
os.mkdir(name)
with open(f"{name}\\req.txt","w") as f:
f.write(req)
with open(f"{name}\\steps.txt","w") as f2:
f2.write(steps)
os.mkdir(f"{name}\\main")
with open(f"{name}\\main\\main.py","w") as f3:
f3.write(f"#Main .py file of {name} project")
elif name in os.listdir():
messagebox.showerror("Project already exists", "A project with this name already exists! Try something else")
elif name=="" or req=="" or steps=="":
messagebox.showerror("Naming error", "Project name/steps/requirement can't be left blank")
print(files)
for fi in files:
copy(fi, name)
#<----Frames---->
head = Frame(WIN, padx=15,pady=10)
head.pack()
main_frame1 = Frame(WIN)
main_frame1.pack()
main_frame2 = Frame(WIN,highlightbackground="black" , highlightthickness=1)
main_frame2.pack()
name_frame = Frame(main_frame1,highlightbackground="black" , highlightthickness=1,padx=382,pady=3)
name_frame.pack()
requirements_frame = Frame(main_frame2)
requirements_frame.grid(row=0,column=0)
files_frame = Frame(main_frame2,highlightbackground="black", highlightthickness=1)
files_frame.grid(row=0,column=1)
#<----Title---->
title = Label(head, text="Project Planner", font=("Arial bold",18))
title.pack()
#<----Name-Frame---->
name_lb = Label(name_frame,text="Project name: ").grid(row=0,column=0,sticky="e")
name_ent = Entry(name_frame,width=20)
name_ent.grid(row=0,column=1)
#<----Requirements---->
requirements_lb = Label(requirements_frame, text="Requirements: ")
requirements_lb.pack()
text_box = Text(requirements_frame,width=100,height=5)
text_box.pack(side = TOP, expand = True, fill = BOTH)
#<----Step---->
step_lb = Label(requirements_frame,text="Steps/Ideas to solve: ")
step_lb.pack()
text_box_step = Text(requirements_frame,width=100,height=17)
text_box_step.pack(side = TOP, expand = True, fill = BOTH)
#<----Files---->
files_lb = Label(files_frame,text="Add files: ")
files_lb.pack()
text_box_files = Text(files_frame,width=20)
text_box_files.pack()
add = Button(files_frame,text="Add",command=Addfile)
add.pack(ipadx=30)
#<----Submit---->
submit = Button(WIN,text="Submit",command=submit)
submit.pack(ipadx=30,pady=2)
WIN.mainloop()
Also my operating system is Windows,
Please help.

Related

Word file keyword or text importing and save to excel sheet using python gui tkinter

I created a python gui using tkinter, the gui gui is showing but during i need to locate the Microsoft word files containing the .docx and .doc it can't see but empty folder. The importing and extraction will not proceed since it doesn't see the word files.
I install the modules,
as python script shown below. Any idea?
Analyze Python Program Requested
import docx
import openpyxl
import os
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog
import threading
import win32com.client
Set the default directory and output location
default_directory = '/path/to/default/directory'
output_location = None
Create the GUI
root = tk.Tk()
root.geometry("300x250")
root.title('Data Extractor')
Create a label to display the current directory
label = tk.Label(root, text='Directory: ' + default_directory)
label.pack()
Create a button to select the directory
def select_directory():
global default_directory
directory = filedialog.askdirectory()
if directory:
default_directory = directory
label.config(text='Directory: ' + default_directory)
button = tk.Button(root, text='Set Directory', command=select_directory)
button.pack()
Create a button to select the output location
def select_output_location():
global output_location
output_location = filedialog.asksaveasfilename(defaultextension='.xlsx', filetypes=[("Excel Workbook", "*.xlsx")])
if output_location:
output_label.config(text='Output: ' + output_location)
output_label = tk.Label(root, text='Output: ')
output_label.pack()
output_button = tk.Button(root, text='Set Output Location', command=select_output_location)
output_button.pack()
Create a progress bar
progress = ttk.Progressbar(root, length=200)
progress.pack()
Create a button to start the extraction
def extract_data():
if default_directory and output_location:
thread = threading.Thread(target=extract_data_thread)
thread.start()
else:
tk.messagebox.showerror("Error", "Please select the directory, output location and check if it contain word files")
def extract_data_thread():
# Create a new Excel workbook
workbook = openpyxl.Workbook()
# Create a new sheet
sheet = workbook.create_sheet()
# Set the starting row for the data
row = 1
# Set the directory to the default or selected directory
directory = default_directory
# Get the number of files to process
file_count = 0
for root, dirs, files in os.walk(directory):
file_count += len([f for f in files if f.endswith(('.docx', '.doc'))])
# Set the progress bar maximum value
progress['maximum'] = file_count
progress['value'] = 0
processed_files = 0
# Iterate over the files in the directory
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.endswith(('.docx', '.doc')):
try:
if filename.endswith('.docx'):
doc = docx.Document(os.path.join(root, filename))
tables = doc.tables
elif filename.endswith('.doc'):
word = win32com.client.Dispatch("Word.Application")
doc = word.Documents.Open(os.path.join(root, filename))
tables = doc.Tables
else:
continue
if tables:
table = tables[0]
model_no = table.cell(0,1).text
reference_number = table.cell(0,2).text
date_released = table.cell(1,1).text
else:
continue
except:
print("An error occurred while processing file: " + filename)
continue
# Add the data to the sheet
sheet.cell(row=row, column=1).value = filename
sheet.cell(row=row, column=2).value = model_no
sheet.cell(row=row, column=3).value = reference_number
sheet.cell(row=row, column=4).value = date_released
# Increment the row counter
row += 1
# Update the progress bar
processed_files += 1
progress.set(processed_files)
root.update()
if processed_files == 0:
tk.messagebox.showerror("Error", "No word files or keyword detected")
else:
# Save the workbook
workbook.save(output_location)
progress['value'] = 0
print("Successfully saved data to: " + output_location)
Create the "Extract Data" button
extract_button = tk.Button(root, text='Extract Data', command=extract_data)
extract_button.pack()
root.mainloop()
any idea how solve the issue?

why is the location string not showing in the window. tkinter python?

im trying to write a code that will tell you if the location is a file or directory. if its a file, then it will read the file. here is my code (ik its very bad, im sorry)
import os
import tkinter as tk
screen = tk.Tk()
screen.title("files and directories")
screen.geometry("300x100")
def FileDir():
path = location.get(1.0, "end-1c")
location.delete(1.0, tk.END)
if os.path.exists(path):
print("✔ - this location exists")
info_location = tk.Label(screen, text=f"location: {location}")
info_location.pack()
if os.path.isfile(path):
print("\tthis is a file")
type = 'file'
info_type = tk.Label(screen, text=f"type: {type}")
info_type.pack()
while True:
open_file = input("\nDo you want to read this file? ")
if open_file.lower() == 'yes':
with open(path) as file:
contents = file.read()
print(contents)
break
elif open_file.lower() == 'no':
print("goodbye!")
break
else:
print("invalid input")
continue
elif os.path.isdir(path):
print("\tthis is a directory")
type = 'directory'
info_type = tk.Label(screen, text=f"type: {type}")
info_type.pack()
else:
print("✘ - this location doesn't exist")
text = tk.Label(screen, text="Enter file/directory location: ")
text.pack()
location = tk.Text(screen, height = 1, width = 25)
location.pack()
enter_btn = tk.Button(screen, text="Enter", command=FileDir)
enter_btn.pack()
screen.mainloop()
so when putting the location of a string, everything works fine except that the location doesnt show and instead it shows ".!text". anyone know why?
location is a widget rather than a string. The string representation of a tkinter widget is its internal name. Thus, when you do text=f"location: {location}" you are creating a string that contains the name of the widget rather than the contents.
To display the contents you must fetch them from the widget. You're already doing that when you define path, so you just need to use {path} rather than {location}
text=f"location: {path}"

UnboundLocalError: local variable 'file1' referenced before assignment please help to fix

I need that when the button is clicked, the file_name variable is saved to a file. Please tell me how to fix my code:
window = tk.Tk()
window.title("Open")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def openu():
global file_name
if file_name == "":
file_name = tfd.askopenfilename()
with open("Filen.json", "w") as file1:
json.dump(file_name, file1, indent=2, ensure_ascii=False)
os.startfile(file_name)
else:
with open("Filen.json", "r") as file1:
json.load(file1)
os.startfile(file_name)
if btn1["text"] == "":
btn1["text"] = file_name
btn1 = tk.Button(window, text="", command=openu)
btn1.place(x = 20, y = 25)
window.mainloop()
UPD:
When you click on the button, the program opens a dialog box that opens the file. A File.json is created. Everything is displayed, but one thing does not work. I need that when restarting the program, the buttons are not empty. I changed the code, putting the full one.
Here is the code. When the user opens the window, it loads the file path from the json file and automatically sets the button's text. When the user presses the button, it asks for a new file path name. More detailed explanations can be found in the comments in the code.
import tkinter as tk
import tkinter.filedialog as tfd
import json
import os
window = tk.Tk()
window.title("Open")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def load_json():
global file_name
# Load the json file if it exists
if os.path.exists("Filen.json"):
with open("Filen.json") as file1:
contents = json.load(file1)
# If the json has a path in it, load the path to file_name
# Otherwise, set file_name to an empty string ""
if len(contents) > 0:
if contents[0] != "":
file_name = contents[0]
else:
file_name = ""
else:
file_name = ""
# Create the json file if it does not exist
else:
with open("Filen.json", "w") as file1:
json.dump([file_name], file1, indent=2, ensure_ascii=False)
def openu():
global file_name
# Load the json file
load_json()
# If file_name is still "", ask the user to input a file path
path = tfd.askopenfilename()
# If the user gave a path (did not hit Cancel), save path to file_name
# and set the button's label
if path != ():
file_name = path
btn1.config(text=file_name)
# Save file_name to the json file
with open("Filen.json", "w") as file1:
json.dump([file_name], file1, indent=2, ensure_ascii=False)
# Load the json file, and put the file name into the button's text
load_json()
btn1 = tk.Button(window, text=file_name, command=openu)
btn1.place(x = 20, y = 25)
window.mainloop()

The name of the application on the button

Is it possible to make the file name appear instead of the path, and I didn't damage the json path?
For example: C:users/desktop/book.txt.
I would like to make it so that only the name is displayed, for example, book,txt. The name, and that is, the file_name variable is displayed on the button.
The code is fully working.
my code:
import tkinter as tk
import tkinter.filedialog as tfd
import json
import os
window = tk.Tk()
window.title("Open")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def load_json():
global file_name
if os.path.exists("Filen.json"):
with open("Filen.json") as file1:
contents = json.load(file1)
if len(contents) > 0:
if contents[0] != "":
file_name = contents[0]
else:
with open("Filen.json", "w") as file1:
json.dump([file_name], file1, indent=2, ensure_ascii=False)
def openu():
global file_name
load_json()
if file_name == "":
path = tfd.askopenfilename()
if path != ():
file_name = path
btn1.config(text=file_name)
else:
os.startfile(file_name)
with open("Filen.json", "w") as file1:
json.dump([file_name], file1, indent=2, ensure_ascii=False)
load_json()
btn1 = tk.Button(window, text=file_name, command=openu)
btn1.place(x = 20, y = 25)
You can extract the file name easily if you have path like below.
import os
file_name = os.path.basename(your_path)
If you have a path C:users/desktop/book.txt then you will get file name as shown below.
file_name=os.path.basename('C:users/desktop/book.txt')
You can extract the filename from the path as follows:
path = "C:users/desktop/book.txt"
filename = path.split("/")[-1]
print(filename)

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!

Categories