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)
Related
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.
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()
I am having some issues passing an argument in a python script to take a specific file like a csv, txt, or xml
I am reviewing python and would like some feedback on why I don't see any output after running the following command: ./my_script some3455.csv
#!/usr/bin/python
import sys
import csv
import xml.etree.ElementTree as ET
FILE = str(sys.argv[1])
def run_files():
if FILE == '*.csv'
run_csv()
elif FILE == '*.txt'
run_txt()
else
run_xml()
def run_csv():
csv_file = csv.register_dialect('dialect', delimiter = '|')
with open(FILE, 'r') as file:
reader = csv.reader(file, dialect='dialect')
for row in reader:
print(row)
def run_txt():
with open(FILE, 'r') as file:
txt_contents = file.read()
print(txt_contents)
def run_xml():
tree = ET.parse(FILE)
root = tree.getroot()
for child in root.findall('Attributes')
car = child.find('Car').text
color = child.find('Color').text
print(car, color)
I have tried to pass it as without the FILE but works just for one and the other file types doesn't get identify.
You need to use fnmatch and not == to compare a string with a glob pattern:
import fnmatch
def run_files():
if fnmatch.fnmatch(FILE, '*.csv'):
run_csv()
elif fnmatch.fnmatch(FILE, '*.txt'):
run_txt()
else:
run_xml()
I have a python script that reads a file and copies its content to another file while deleting unwanted lines before sending.
The problem is that I want to allow the user to choose the source file and the destination path.
How can this be solved ?
outputSortedFiles.py
#!/usr/bin/python
'''FUNCTION THAT READ SELECTE DFILE AND WRITE ITS
CONTENT TO SECOND FILE WITH DELETING
TH EUNWANTED WORDS'''
import Tkinter
from os import listdir
from os.path import isfile
from os.path import join
import tkFileDialog
import os
def readWrite():
unwanted = ['thumbnails', 'tyroi', 'cache', 'Total files', 'zeryit', 'Ringtones', 'iconRecv',
'tubemate', 'ueventd', 'fstab', 'default', 'lpm']
mypath = r"C:\Users\hHJE\Desktop/filesys"
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfile(initialdir = mypath, filetypes=[('text files', ' TXT ')])
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in files:
if file.split('.')[1] == 'txt':
outputFileName = 'Sorted-' + file
with open(mypath + outputFileName, 'w') as w:
with open(mypath + '/' + file) as f:
for l in f:
if not True in [item in l for item in unwanted]:
w.write(l)
print ("
*********************************\
THE OUTPUT FILE IS READY\
*********************************\
")
in_path.close()
if __name__== "__main__":
readWrite()
You can use TkFileDialog just as you did to ask inputFiles :
outputpath = tkFileDialog.asksaveasfile()
See examples in those tutorials : http://www.tkdocs.com/tutorial/windows.html
If you simply want the user to choose the directory:
from tkinter import filedialog
outputpath = filedialog.askdirectory()
I have the following piece of code:
def run(self):
filename = QtGui.QFileDialog.getSaveFileName(self, "Save file", "", ".inp")
if filename == "":
pass
elif filename != "":
nfile = open(filename, 'w')
self.pixmap1 = QtGui.QPixmap('yellow.jpg')
self.canvas1.setPixmap(self.pixmap1)
self.cursor.movePosition(self.cursor.Start, self.cursor.MoveAnchor)
self.cursor.movePosition(self.cursor.End, self.cursor.KeepAnchor)
text = self.cursor.selection()
text1 = text.toPlainText()
nfile.write(text1)
nfile.close()
fileInfo = QtCore.QFileInfo(filename)
name = fileInfo.baseName()
import os
os.system("rungms {}.inp 13-64 {} {} {}.out".format(name, self.cores_val, self.clusters_val, name))
from itertools import islice
import sys
with open("{}.out".format(name)) as searchfile:
for line in searchfile:
if 'TERMINATED NORMALLY' in line:
self.pixmap1 = QtGui.QPixmap('green.jpg')
self.canvas1.setPixmap(self.pixmap1)
elif 'job aborted' in line:
self.pixmap1 = QtGui.QPixmap('red.jpg')
self.canvas1.setPixmap(self.pixmap1)
else:
pass
else:
pass
My problem is that the two lines involving QPixmap('yellow.jpg') are not being read after saving my file. However, if I move these two lines in between the first and second lines of the code (i.e. before filename = QtGui...), then they do work.
Can someone explain to me why this is the case?