How to use open function with path include space - python

I'M try to make a program that works with drag file into gui and create a hash code for it. But if path of file has space in it, then it goes error. How can i fix this
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\c9947515\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "C:\Users\c9947515\Desktop\Phyton\pythonProject1\dosya hash.py", line 19, in on_drop
with open(file_path, "rb") as file:
^^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 22] Invalid argument: '{C:/Users/c9947515/Desktop/Wire Text.txt}'
import tkinterdnd2 as tk
import tkinter as tk2
import hashlib
root = tk.Tk()
root.title("File Hash Calculator")
root.geometry("400x150")
root.drop_target_register(tk.DND_FILES)
def on_drop(event):
file_path = event.data
# Dosya yolunu oku ve dosya içeriğini oku
with open(file_path, "rb") as file:
data = file.read()
# Dosya içeriğine göre SHA1 değerini hesapla
sha1_hash = hashlib.sha1(data).hexdigest()
# SHA1 değerini inputbox'a yazdır
input_box.insert(0, sha1_hash)
# Dosya sürükleyip bırakıldığında tetiklenecek fonksiyonu ata
root.dnd_bind("<<Drop>>", on_drop)
# Açıklama yazısı oluştur
label = tk2.Label(root, text="Drag and drop a file to calculate its SHA1 hash:")
label.pack()
# Giriş alanı oluştur
input_box = tk2.Entry(root)
input_box.pack()
# Pencerenin çalışmasını sağla
root.mainloop()

It is added by the underlying TCL interpreter when there are spaces in the string. You can remove them using .strip("{}"):
file_path = event.data.strip("{}")

{ and } are being added to your paths.
If you use file_path = file_path.replace("{", "").replace("}", "")
then it will not handle files with { or } anywhere in the filename. Use removeprefix and removesuffix instead to avoid this problem.
This will work:
import tkinterdnd2 as tk
import tkinter as tk2
import hashlib
root = tk.Tk()
root.title("File Hash Calculator")
root.geometry("400x150")
root.drop_target_register(tk.DND_FILES)
def on_drop(event):
if event.data.startswith('{') and event.data.endswith('}'):
file_path = event.data.removesuffix('}').removeprefix('{')
else:
file_path = event.data
# Dosya yolunu oku ve dosya içeriğini oku
with open(file_path, "rb") as file:
data = file.read()
# Dosya içeriğine göre SHA1 değerini hesapla
sha1_hash = hashlib.sha1(data).hexdigest()
# SHA1 değerini inputbox'a yazdır
input_box.insert(0, sha1_hash)
# Dosya sürükleyip bırakıldığında tetiklenecek fonksiyonu ata
root.dnd_bind("<<Drop>>", on_drop)
# Açıklama yazısı oluştur
label = tk2.Label(root, text="Drag and drop a file to calculate its SHA1 hash:")
label.pack()
# Giriş alanı oluştur
input_box = tk2.Entry(root)
input_box.pack()
# Pencerenin çalışmasını sağla
root.mainloop()

Related

How to make a new .py file

I want to make new file but first choose directory.
This code works but a directory is already set
new_file = input("File name\n")
new_file = new_file.lower().replace(".", "").replace(" ", "_")
print(new_file)
open_file = open('D:\Python projects\%s.py' % new_file, 'w')
Also tried like this but not happen
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
new_file = input("Name file\n")
open_file = open(f"{file_path}\%s.py" % new_file, 'w')
askdirectory should work. file_path = filedialog.askdirectory

Only one file decrypting in for loop

I have an issue with my program.
Whenever I encrypt multiple files, it works flawlessly; when I decrypt the files however, it fails pretty hard. No errors or anything.
The issue is just;
Only one file decrypts, no more. The rest of the files do look decrypted, but at the same time ?not?
Here is an example image of what shows when I decrypted a text file with pi to 1m digits. This only happens when decrypting multiple files.
Finally, here is the code. Big thanks to anyone willing to be helpfull!!! :)
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
import sys
import os.path
from tkinter import *
import tkinter.filedialog as fd
from tkinter import ttk
from tkinter import messagebox
from PIL import ImageTk,Image
from os import startfile
# Just some path defining stuff
user_profile = os.environ['USERPROFILE']
user_desktop = user_profile + "\\Documents"
os.chdir(sys.path[0])
save_path = f'{sys.path[0]}/TestEncrypted'.replace("\\","/")
save_path2 = f'{sys.path[0]}/TestDecrypted'.replace("\\","/")
# Create directories for encrypted/decrypted files
try:
os.mkdir(save_path)
except:
print(f'Directory: {save_path} already exists')
try:
os.mkdir(save_path2)
except:
print(f'Directory: {save_path2} already exists')
def padkey(key):
global oldkey
oldkey = key
while len(key)% 16 != 0:
key+= " "
return key
def encrypt1():
"""
Loops over files for encryption.
"""
newkey = padkey('testpass').encode('UTF-8')
cipher = AES.new(newkey,AES.MODE_CBC)
# Create for loop here!!!
filez = fd.askopenfilenames(parent=root, title='Choose files to encrypt',initialdir = user_desktop)
for filename in filez:
try:
with open(filename, 'rb') as f:
rfile = f.read()
f.close()
except:
messagebox.showerror("ITExtra Popup", "You didn't select a file")
ciphertext = cipher.encrypt(pad(rfile, AES.block_size))
encryptfilename = filename.split('/')[-1]+'.ENCRYPTED'
completeName = os.path.join(save_path, encryptfilename).replace("\\","/")
print(completeName)
with open(completeName,'wb') as c_file:
c_file.write(cipher.iv)
c_file.write(ciphertext)
c_file.close()
label2=Label(root,text=(save_path+"/"+encryptfilename).replace('\\','/').lower(),font='Helvetica 13 bold italic',fg='BLUE',bg='black').place(relx=0,rely=0.88)
return
def decrypt1():
"""
Loops over files for decryption.
"""
faildec = 0
succdec = 0
filez2 = fd.askopenfilenames(parent=root, title='Choose files to decrypt',initialdir = save_path)
for decryptfilename in filez2:
newkey = padkey('testpass').encode('UTF-8')
# Decrypt file
try:
with open(decryptfilename,'rb') as c_file:
iv = c_file.read(16)
ciphertext = c_file.read()
c_file.close()
except:
faildec +=1
cipher = AES.new(newkey,AES.MODE_CBC, iv)
rfile = unpad(cipher.decrypt(ciphertext),AES.block_size)
# Input extension and save file
filename = decryptfilename.split('/')[-1].replace('.ENCRYPTED', '')
completeName2 = os.path.join(save_path2, filename)
with open(completeName2, 'wb') as writefile:
writefile.write(rfile)
writefile.close()
label2=Label(root,text=(save_path2+"/"+filename).replace("\\","/").lower(),font='Helvetica 10 bold italic',fg='BLUE',bg='black').place(relx=0,rely=0.88)
succdec +=1
response2 = messagebox.askyesno("ITExtra Popup", f"""Do you want to open the 'Decrypted' directory?\n{save_path2}
Successful decryptions = {succdec}
Failed decryptions = {faildec}
""")
if response2 == 1:
startfile(save_path2)
return
print(sys.path[0])
print(save_path)
print(save_path2)
print(user_desktop)
root = Tk()
w = 850 # width for the Tk root
h = 310 # height for the Tk root
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
x = (ws/2) - (w/2)
y = (hs/3) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
frame1=LabelFrame(root,bd=0,bg='#000000')
but1 = Button(frame1, text="ENCRYPT file", padx=30, pady=10, bg="#1f1f1f",fg="red",font='Helvetica 15 bold', command=encrypt1,relief=FLAT)
but2 = Button(frame1, text="DECRYPT file", padx=30, pady=10, bg="#1f1f1f",fg="green",font='Helvetica 15 bold', command=decrypt1,relief=FLAT)
but1.grid(row=2,column=0,padx=1,pady=5) # Encrypt FILE #
but2.grid(row=2,column=2,pady=5) # Decrypt FILE #
frame1.place(relx=0.20,rely=0.5)
root.mainloop()
Edit
Removed except statements for debugging purposes.

How can i detect if a file has already been opened in python

I hope you can help me, I'm new on python.
I am making a program in python with tkinter that requires opening a file and then converting it.
My problem is the conditional, because I need that when pressing the "Convert file" button it checks if the file has been selected first and if not, it shows a message that says "No file has been opened".
I think the problem is in the return opened_file_path. How can I make the string variable of the file path available to any function?
Here is my code, thank you.
from tkinter import filedialog
from tkinter import messagebox
from tkinter import *
import os
import re
window = Tk()
window.title("Blank-Space UXD deleter (beta)")
window.geometry('400x50')
def open_file():
opened_file_path=filedialog.askopenfilename(initialdir = "/",
title = "Select files",filetypes = (("TXT files","*.txt"),
("All files","*.*")))
return opened_file_path
def convert_file():
if opened_file_path == "":
messagebox.showinfo(message="No file has been opened", title="Imposible to convert")
else:
file_name = opened_file_name
file_name_mod = file_name.replace(".txt", "")
file_name_mod = file_name_mod + "m.txt"
mod_file = open(file_name_mod, 'w')
raw_file = open(file_name, 'r')
for x in raw_file:
xf = re.sub(' +', ' ', x)
xf = xf.lstrip()
mod_file.write(xf)
print(x)
print(xf)
Button(text="Open file",command=open_file).place(x=10,y=10)
Button(text="Convert file",command=convert_file).place(x=150,y=10)
window.mainloop()

how to fix 'fp.seek(self.start_dir, 0) OSError: [Errno 22] Invalid argument' in python

I'm writing a python application to unzip zip archive files but am getting an error.
I've tried renaming the file and removing parts of the script that are unnecessary.
My script is :
import zipfile
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as mgb
import tkinter.filedialog as tkfd
OutputPath = ""
ZIPFile = ""
root = tk.Tk()
def OpenFile() :
global ZIPFile
global OutputPath
ZIPFile = tkfd.askopenfilename(initialdir = "/",title = "Select file")
if OutputPath != "" and ZIPFile != "" : ZipBut.state(["!disabled"])
def OutputFile() :
global OutputPath
global ZIPFile
OutputPath = tkfd.askdirectory(initialdir = "/", title = "Select file")
if OutputPath != "" and ZIPFile != "" : ZipBut.state(["!disabled"])
def unzip() :
global ZIPFile
global OutputPath
with zipfile.ZipFile(ZIPFile) as File :
File.extractall(path = OutputPath)
CommandBar = ttk.Frame(root)
CommandBar.pack()
ttk.Button(CommandBar, text = "open", command = OpenFile).grid(row = 0, column = 0)
ttk.Button(CommandBar, text = "output", command = OutputFile).grid(row = 0, column = 1)
ZipBut = ttk.Button(CommandBar, text = "unzip", command = unzip)
ZipBut.grid(row = 0, column = 2)
ZipBut.state(["disabled"])
root.mainloop()
Im Expecting the file to unzip into a folder of choice however get a Exception
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\dell\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1558, in __call__
return self.func(*args)
File "C:/Users/dell/Desktop/ZIP/main.pyw", line 29, in unzip
with zipfile.ZipFile(ZIPFile) as File :
File "C:\Users\dell\AppData\Local\Programs\Python\Python35-32\lib\zipfile.py", line 1026, in __init__
self._RealGetContents()
File "C:\Users\dell\AppData\Local\Programs\Python\Python35-32\lib\zipfile.py", line 1111, in _RealGetContents
fp.seek(self.start_dir, 0)
OSError: [Errno 22] Invalid argument

tkinter drop down menu from excel

I want to use tkinter to browse an excel sheet and make a drop down menu of the rows of that excel sheet.
I am pretty new to python and do not know how to work it through. The code until now looks like this:
import xlrd
import os
from subprocess import call
import Tkinter,tkFileDialog
root = Tkinter.Tk()
root.withdraw()
filename = tkFileDialog.askopenfiles(title='Choose an excel file')
print(filename)
print type(filename)
#file = str(filename)
file = [filetypes for filetypes in filename if ".xlsx" in filetypes]
workbook = xlrd.open_workbook(filename)
for file in filename:
sheet = workbook.sheet_by_index(0)
print(sheet)
for value in sheet.row_values(0):
print(value)
This throws an error:
Traceback (most recent call last):
File "C:/Geocoding/test.py", line 14, in
workbook = xlrd.open_workbook(filename)
File "C:\Python27\ArcGIS10.3\lib\site-packages\xlrd__init__.py", line 394, in open_workbook
f = open(filename, "rb")
TypeError: coercing to Unicode: need string or buffer, list found
I am not even able to read the excel sheet that the user browses. I have no idea why this error. I would really appreciate if anybody can help me with it. Am I on the right path ?
Thanks
The new code that works:
import xlrd
from Tkinter import *
import Tkinter,tkFileDialog
root = Tkinter.Tk()
root.withdraw()
filename = tkFileDialog.askopenfilename(title='Choose an excel file')
print(filename)
print type(filename)
#file = str(filename)
file = [filetypes for filetypes in filename if ".xlsx" in filetypes]
workbook = xlrd.open_workbook(filename)
#for file in filename:
sheet = workbook.sheet_by_index(0)
print(sheet)
for value in sheet.row_values(0):
print(value)
print(type(value))
master = Tk()
variable=StringVar(master)
#variable=sheet.row_values(0)[0]
variable.set(sheet.row_values(0)[0])
#for var in value:
# variable = StringVar(master)
# variable.set(value) # default value
#w = OptionMenu(master, variable, value)
w = apply(OptionMenu, (master, variable) + tuple(sheet.row_values(0)))
w.pack()
mainloop()
You may have more errors along the way but in your code here:
filename = tkFileDialog.askopenfiles(title='Choose an excel file')
the result from that dialog is a list of file objects. So you are passing that list of fileobjects to open_workbook here:
workbook = xlrd.open_workbook(filename)
Instead what you need to do is pass the name of the file you care about as a string to open_workbook:
workbook = xlrd.open_workbook(filename[0].name) # the name of the first file in the list
here is a working Python3 (sorry I abandoned Python2) example for tkinter to properly select filenames:
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
filename = filedialog.askopenfiles(title='Choose an excel file')
print(filename) # filename is a list of file objects
print(filename[0].name) # this is the name of the first selected in the dialog that you can pass to xlrd

Categories

Resources