0

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:\Users\57314\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__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
1
  • Welcome to Stackoverflow. Right now your code example doesn't directly trigger the error that you're describing. You'll have a better chance of getting good answers if you modify your code example such that it immediately produces the error when the code is run. See How to Create a Minimal, Complete and Reproducible Example for more advice. Commented May 23, 2019 at 20:27

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much for helping me, and thank you for that link, it seems pretty useful. i tried that and i think you're right about my mistake but now this error shows up Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\57314\AppData\Local\Programs\Python\Python37-32\lib\tkinter_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 _io.TextIOWrapper
So what this means is that the function open() is expecting a str, bytes, or os.PathLike object. But we are giving it an already open file object! Looking back at the link I sent, I think you should probably use askopenfilename() instead of the askopenfile() function that I originally suggested. I will update my answer, good catch!
You're right, thank you so much, now i have the problem that it doesn't show the text but the function itself but i'll keep learning so i fix that, thank you again.
In this line: textarea.insert(1.0,file.read), try changing file.read to file.read(). The parentheses will tell the read function to execute instead of just returning the function object itself.
Thank you again, this completely solved the problem, please have a good day.
0

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' )

Comments

0
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()

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.