How can i open a text file on a Notepad made in python?
Question:
I’m trying to add a function that allows me to open a text file on a notepad built in python but this error shows up TypeError: expected str, bytes or os.PathLike object, not list
I’m actually really new to programming and i’m following this tutorial about how to make a notepad on python, i’ve tried importing os but i had no idea how to use it. Thanks in advance
from tkinter import Tk, scrolledtext, Menu, filedialog, END, messagebox
from tkinter.scrolledtext import ScrolledText
from tkinter import*
#Root main window
root = Tk(className=" Text Editor")
textarea = ScrolledText(root, width=80, height=100)
textarea.pack()
# Menu options
menu = Menu(root)
root.config(menu=menu)
filename = Menu(menu)
edicion = Menu(menu)
# Funciones File
def open_file ():
file = filedialog.askopenfiles(parent=root, mode='r+', title="Select a file")
if file == None:
contenidos = file.read()
textarea.insert('1.0', contenidos)
file.close
else:
root.title(" - Notepad")
textarea.delete(1.0,END)
file = open(file,"r+")
textarea.insert(1.0,file.read)
file.close()
def savefile ():
file = filedialog.asksaveasfile(mode='w')
if file!= None:
data = textarea.get('1.0',END+'-1c')
file.write(data)
file.close()
def exit():
if messagebox.askyesno ("Exit", "Seguro?"):
root.destroy()
def nuevo():
if messagebox.askyesno("Nuevo","Seguro?"):
file= root.title("Vistima")
file = None
textarea.delete(1.0,END)
#Funciones editar
def copiar():
textarea.event_generate("<<Copy>>")
def cortar():
textarea.event_generate("<<Cut>>")
def pegar():
textarea.event_generate("<<Paste>>")
#Menu
menu.add_cascade(label="File", menu=filename)
filename.add_command(label="New", command = nuevo)
filename.add_command(label="Open", command= open_file)
filename.add_command(label="Save", command=savefile)
filename.add_separator()
filename.add_command(label="Exit", command=exit)
menu.add_cascade(label="Editar", menu=edicion)
edicion.add_command(label="Cortar", command=cortar)
edicion.add_command(label="Pegar", command=pegar)
edicion.add_command(label="Copiar", command=copiar)
textarea.pack()
#Keep running
root.mainloop()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:Users57314AppDataLocalProgramsPythonPython37-32libtkinter__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/57314/PycharmProjects/text_editor/bucky.py", line 28, in open_file
file = open(file,"r+")
TypeError: expected str, bytes or os.PathLike object, not list
Answers:
The error gives you a hint at what’s happening.
You are getting this error: TypeError: expected str, bytes or os.PathLike object, not list
This suggests that this line:
file = open(file,"r+")
is trying to open a list. Why might that be? Well, the function you are using here to assign the file
variable is returning a list of files not a single filename:
file = filedialog.askopenfiles(parent=root, mode='r+', title="Select a file")
Is there a chance you misread the tutorial and you should have written:
file = filedialog.askopenfilename(parent=root, mode='r+', title="Select a file")
Check out the subtle difference between the two functions here: http://epydoc.sourceforge.net/stdlib/tkFileDialog-module.html#askopenfiles.
I made a similar app without GUI but it is the same at the core. Instead of the text entering stuff in tkinter i used standard input function in console. Here’s my readable code:
(Look at my read function)
print('My NoteBook')
print('Note: Do not reuse file names for text will be overwritten.')
import sys
import replit
exit=0
while exit!='y':
m=input('Select an option: a)read your docs or b)write a doc or c)delete a doc ')
def writes():
title=input('Enter the title of this paper: ')
textstuff = input('Write something: ')
text_file = open(title,'w')
text_file.write(textstuff)
text_file.close()
def read():
inputFileName = input("Enter name of paper: ")
inputFile = open(inputFileName, "r")
for line in inputFile:
sys.stdout.write(line)
def delete():
import os
print("Enter the Name of Paper: ")
filename = input()
os.remove(filename)
print("nPaper deleted successfully!")
if m=='a':
read()
elif m=="b":
writes()
else:
delete()
exit=input('nDo you want to exit, y/n ')
replit.clear()
sys.exit('Thank you' )
I made an example of a text editor with tkinter.
You can look at the reading function.
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
import os
# Creating the window
window = Tk()
window.title("Notepad")
window.geometry("500x500")
# Creating Text area
text_changed = False
text_area = Text(window, font="Calibri 15", wrap=None, undo=True)
text_area.pack(expand=True, fill=BOTH)
file = None
text_area.focus_force()
# Creating Functions for File menu
def new():
global text_changed
if text_changed == False:
text = text_area.get(1.0, END)
text_area.delete(1.0, END)
window.title("Untitled - Notepad")
else:
save_the_file = messagebox.askyesnocancel(
"Notepad", "Do you want to save the changes to Untitled?"
)
if save_the_file == True:
file = filedialog.askopenfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("Text Documents", ".txt"), ("All Types", "*.*")],
)
f = open(file, "w")
f.write(text_area.get(1.0, END))
f.close()
text_area.delete(1.0, END)
text_area.edit_modified(False)
elif save_the_file == False:
text = text_area.get(1.0, END)
text_area.delte(1.0, END)
window.title("Untitled - Notepad")
text_changed = False
text_area.edit_modified(False)
else:
pass
def open():
try:
global file, text_changed
file = filedialog.askopenfilename(
defaultextension=".txt",
filetypes=[("Text Documents", ".txt"), ("All Types", "*.*")],
)
if file == "":
file = None
else:
window.title(os.path.basename(file) + " - Notepad")
changed_title = False
text_area.delete(1.0, END)
f = open(file, "r")
text_area.insert(1.0, f.read())
text_changed = False
except:
messagebox.showerror("Error", "Can't open the file!")
window.title("Untitled - Notepad")
def save():
global file
if file == None:
file = filedialog.asksaveasfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", ".txt")],
)
if file == "":
file = None
else:
f = open(file, "w")
f.write(text_area.get(1.0, END))
f.close()
window.title(os.path.basename(file) + " - Notepad")
else:
f = open(file, "w")
f.write(text_area.get(1.0, END))
f.close()
window.title(os.path.basename(file + " - Notepad"))
def save_as():
global file
file = filedialog.asksaveasfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("Text Documents", "*.txt"), ("All Types", "*.*")],
)
if file != "":
f = open(file, "w")
f.write(text_area.get(1.0, END))
f.close()
def exit():
global file
if file:
window.wm_protocol("WM_DELTE_WINDOW", exit)
msg = messagebox.askyesnocancel(
"Warning", "Do you want to save the changes to Untitled?"
)
if msg == True:
ask_user = filedialog.asksaveasfilename(
defaultextension=".txt",
filetype=[("Text Documents", "*.txt"), ("All Types", "*.*")],
)
if ask_user == "":
window.quit()
else:
window.title(os.path.basename(ask_user))
f = open(ask_user, "w")
f.write(text_area.get(1.0, END))
f.close()
window.quit()
elif msg == False:
window.quit()
else:
window.quit()
# Creating functions for Edit menu
def cut():
text_area.event_generate(("<<Cut>>"))
def copy():
text_area.event_generate(("<<Copy>>"))
def paste():
text_area.event_generate(("<<Paste>>"))
def delete():
text_area.delete(0.0, END)
def undo():
text_area.edit_undo()
def redo():
text_area.edit_redo()
def select_all():
text_area.tag_add("sel", "1.0", "end")
# Creating functions for Help menu
def help():
messagebox.showinfo("info", "This is an example of Notepad.")
# Creating the Menu
menu = Menu(window)
# Adding File nenu and commands
file = Menu(menu, tearoff=0, font=("Calibri", 12))
menu.add_cascade(label="File", menu=file)
file.add_command(label="New", command=new)
file.add_command(label="Open", command=open)
file.add_command(label="Save", command=save)
file.add_command(label="Save As", command=save_as)
file.add_separator()
file.add_command(labe="Exit", command=exit)
# Ading Edit menu and comands
edit = Menu(menu, tearoff=0, font=("Calibri", 12))
menu.add_cascade(label="Edit", menu=edit)
edit.add_command(label="Cut", command=cut)
edit.add_command(label="Copy", command=copy)
edit.add_command(label="Paste", command=paste)
edit.add_command(label="Delete", command=delete)
edit.add_separator()
edit.add_command(label="Undo", command=undo)
edit.add_command(label="Redo", command=redo)
edit.add_separator()
edit.add_command(label="Select all", command=select_all)
# Ading Help menu and comands
_help = Menu(menu, tearoff=0, font=("Calibri", 12))
menu.add_cascade(label="Help", menu=_help)
_help.add_command(label="About", command=help)
window.config(menu=menu)
window.mainloop()
I’m trying to add a function that allows me to open a text file on a notepad built in python but this error shows up TypeError: expected str, bytes or os.PathLike object, not list
I’m actually really new to programming and i’m following this tutorial about how to make a notepad on python, i’ve tried importing os but i had no idea how to use it. Thanks in advance
from tkinter import Tk, scrolledtext, Menu, filedialog, END, messagebox
from tkinter.scrolledtext import ScrolledText
from tkinter import*
#Root main window
root = Tk(className=" Text Editor")
textarea = ScrolledText(root, width=80, height=100)
textarea.pack()
# Menu options
menu = Menu(root)
root.config(menu=menu)
filename = Menu(menu)
edicion = Menu(menu)
# Funciones File
def open_file ():
file = filedialog.askopenfiles(parent=root, mode='r+', title="Select a file")
if file == None:
contenidos = file.read()
textarea.insert('1.0', contenidos)
file.close
else:
root.title(" - Notepad")
textarea.delete(1.0,END)
file = open(file,"r+")
textarea.insert(1.0,file.read)
file.close()
def savefile ():
file = filedialog.asksaveasfile(mode='w')
if file!= None:
data = textarea.get('1.0',END+'-1c')
file.write(data)
file.close()
def exit():
if messagebox.askyesno ("Exit", "Seguro?"):
root.destroy()
def nuevo():
if messagebox.askyesno("Nuevo","Seguro?"):
file= root.title("Vistima")
file = None
textarea.delete(1.0,END)
#Funciones editar
def copiar():
textarea.event_generate("<<Copy>>")
def cortar():
textarea.event_generate("<<Cut>>")
def pegar():
textarea.event_generate("<<Paste>>")
#Menu
menu.add_cascade(label="File", menu=filename)
filename.add_command(label="New", command = nuevo)
filename.add_command(label="Open", command= open_file)
filename.add_command(label="Save", command=savefile)
filename.add_separator()
filename.add_command(label="Exit", command=exit)
menu.add_cascade(label="Editar", menu=edicion)
edicion.add_command(label="Cortar", command=cortar)
edicion.add_command(label="Pegar", command=pegar)
edicion.add_command(label="Copiar", command=copiar)
textarea.pack()
#Keep running
root.mainloop()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:Users57314AppDataLocalProgramsPythonPython37-32libtkinter__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/57314/PycharmProjects/text_editor/bucky.py", line 28, in open_file
file = open(file,"r+")
TypeError: expected str, bytes or os.PathLike object, not list
The error gives you a hint at what’s happening.
You are getting this error: TypeError: expected str, bytes or os.PathLike object, not list
This suggests that this line:
file = open(file,"r+")
is trying to open a list. Why might that be? Well, the function you are using here to assign the file
variable is returning a list of files not a single filename:
file = filedialog.askopenfiles(parent=root, mode='r+', title="Select a file")
Is there a chance you misread the tutorial and you should have written:
file = filedialog.askopenfilename(parent=root, mode='r+', title="Select a file")
Check out the subtle difference between the two functions here: http://epydoc.sourceforge.net/stdlib/tkFileDialog-module.html#askopenfiles.
I made a similar app without GUI but it is the same at the core. Instead of the text entering stuff in tkinter i used standard input function in console. Here’s my readable code:
(Look at my read function)
print('My NoteBook')
print('Note: Do not reuse file names for text will be overwritten.')
import sys
import replit
exit=0
while exit!='y':
m=input('Select an option: a)read your docs or b)write a doc or c)delete a doc ')
def writes():
title=input('Enter the title of this paper: ')
textstuff = input('Write something: ')
text_file = open(title,'w')
text_file.write(textstuff)
text_file.close()
def read():
inputFileName = input("Enter name of paper: ")
inputFile = open(inputFileName, "r")
for line in inputFile:
sys.stdout.write(line)
def delete():
import os
print("Enter the Name of Paper: ")
filename = input()
os.remove(filename)
print("nPaper deleted successfully!")
if m=='a':
read()
elif m=="b":
writes()
else:
delete()
exit=input('nDo you want to exit, y/n ')
replit.clear()
sys.exit('Thank you' )
I made an example of a text editor with tkinter.
You can look at the reading function.
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
import os
# Creating the window
window = Tk()
window.title("Notepad")
window.geometry("500x500")
# Creating Text area
text_changed = False
text_area = Text(window, font="Calibri 15", wrap=None, undo=True)
text_area.pack(expand=True, fill=BOTH)
file = None
text_area.focus_force()
# Creating Functions for File menu
def new():
global text_changed
if text_changed == False:
text = text_area.get(1.0, END)
text_area.delete(1.0, END)
window.title("Untitled - Notepad")
else:
save_the_file = messagebox.askyesnocancel(
"Notepad", "Do you want to save the changes to Untitled?"
)
if save_the_file == True:
file = filedialog.askopenfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("Text Documents", ".txt"), ("All Types", "*.*")],
)
f = open(file, "w")
f.write(text_area.get(1.0, END))
f.close()
text_area.delete(1.0, END)
text_area.edit_modified(False)
elif save_the_file == False:
text = text_area.get(1.0, END)
text_area.delte(1.0, END)
window.title("Untitled - Notepad")
text_changed = False
text_area.edit_modified(False)
else:
pass
def open():
try:
global file, text_changed
file = filedialog.askopenfilename(
defaultextension=".txt",
filetypes=[("Text Documents", ".txt"), ("All Types", "*.*")],
)
if file == "":
file = None
else:
window.title(os.path.basename(file) + " - Notepad")
changed_title = False
text_area.delete(1.0, END)
f = open(file, "r")
text_area.insert(1.0, f.read())
text_changed = False
except:
messagebox.showerror("Error", "Can't open the file!")
window.title("Untitled - Notepad")
def save():
global file
if file == None:
file = filedialog.asksaveasfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", ".txt")],
)
if file == "":
file = None
else:
f = open(file, "w")
f.write(text_area.get(1.0, END))
f.close()
window.title(os.path.basename(file) + " - Notepad")
else:
f = open(file, "w")
f.write(text_area.get(1.0, END))
f.close()
window.title(os.path.basename(file + " - Notepad"))
def save_as():
global file
file = filedialog.asksaveasfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("Text Documents", "*.txt"), ("All Types", "*.*")],
)
if file != "":
f = open(file, "w")
f.write(text_area.get(1.0, END))
f.close()
def exit():
global file
if file:
window.wm_protocol("WM_DELTE_WINDOW", exit)
msg = messagebox.askyesnocancel(
"Warning", "Do you want to save the changes to Untitled?"
)
if msg == True:
ask_user = filedialog.asksaveasfilename(
defaultextension=".txt",
filetype=[("Text Documents", "*.txt"), ("All Types", "*.*")],
)
if ask_user == "":
window.quit()
else:
window.title(os.path.basename(ask_user))
f = open(ask_user, "w")
f.write(text_area.get(1.0, END))
f.close()
window.quit()
elif msg == False:
window.quit()
else:
window.quit()
# Creating functions for Edit menu
def cut():
text_area.event_generate(("<<Cut>>"))
def copy():
text_area.event_generate(("<<Copy>>"))
def paste():
text_area.event_generate(("<<Paste>>"))
def delete():
text_area.delete(0.0, END)
def undo():
text_area.edit_undo()
def redo():
text_area.edit_redo()
def select_all():
text_area.tag_add("sel", "1.0", "end")
# Creating functions for Help menu
def help():
messagebox.showinfo("info", "This is an example of Notepad.")
# Creating the Menu
menu = Menu(window)
# Adding File nenu and commands
file = Menu(menu, tearoff=0, font=("Calibri", 12))
menu.add_cascade(label="File", menu=file)
file.add_command(label="New", command=new)
file.add_command(label="Open", command=open)
file.add_command(label="Save", command=save)
file.add_command(label="Save As", command=save_as)
file.add_separator()
file.add_command(labe="Exit", command=exit)
# Ading Edit menu and comands
edit = Menu(menu, tearoff=0, font=("Calibri", 12))
menu.add_cascade(label="Edit", menu=edit)
edit.add_command(label="Cut", command=cut)
edit.add_command(label="Copy", command=copy)
edit.add_command(label="Paste", command=paste)
edit.add_command(label="Delete", command=delete)
edit.add_separator()
edit.add_command(label="Undo", command=undo)
edit.add_command(label="Redo", command=redo)
edit.add_separator()
edit.add_command(label="Select all", command=select_all)
# Ading Help menu and comands
_help = Menu(menu, tearoff=0, font=("Calibri", 12))
menu.add_cascade(label="Help", menu=_help)
_help.add_command(label="About", command=help)
window.config(menu=menu)
window.mainloop()