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)
CodePudding user response:
I hope I got it right. You can extract the filename from the path as follows:
path = "C:users/desktop/book.txt"
filename = path.split("/")[-1]
print(filename)
CodePudding user response:
You can extract the file name easily if you have path like below.
import os
file_name = os.path.basename(your_path)