#๐Ÿ”’ can somebody help me with this object creator function. im getting errors and idk hwo to use it

169 messages ยท Page 1 of 1 (latest)

placid idol
#
def bookinfotxtread(book):
        # This method will read the file and create Book objects
            bookslist = []
            filename = book.name + ".txt"
            with open(filename) as bi:
                line_list = bi.readlines()
                
                for line in line_list:
                     book_data = line.strip().split(",")

                     if len(book_data) == 2:  # If there are only 2 values in the file
                        book_data_inside = Book(book_data[0], None, None, None, book_data[1])
                        print(book_data_inside)

                     elif len(book_data) ==5:
                        book_data_inside = Book(*book_data)

Traceback (most recent call last):
  File "c:\Users\anuro\OneDrive - Edgewater College\3TDIG\python stuff\2.3_borrowfinal.py", line 64, in <module>
    hi.bookinfotxtread()
  File "c:\Users\anuro\OneDrive - Edgewater College\3TDIG\python stuff\2.3_borrowfinal.py", line 43, in bookinfotxtread
    with open(filename) as bi:
         ^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '.txt'
PS C:\Users\anuro\OneDrive - Edgewater College\3TDIG\python stuff> 
``` i dont know what is happenig here
barren pecanBOT
#

@placid idol

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

placid idol
#

please dont close channel for now i am in school so i might not be able to respond

zinc scarab
#

Looks like when you called the Book class you start spamming none to all params, so now you have no book name, so basically this line filename = book.name + ".txt" is not doing a thing it just names the book instance to ".txt"

placid idol
#

i do have a file called book.txt so does filename have to be book.txt = book.name = ."txt"

zinc scarab
#

The prob in your instance

placid idol
#

oh ok

zinc scarab
#

In the same dirzctory

#

?

placid idol
zinc scarab
#

Yeah

placid idol
#

all they way at the bottom

#

bookinfo.tzt

#

txt

zinc scarab
#

How about you print out filename right after this line filename =

#

And see what is the value that is passed

placid idol
#

btw why is it open(filename) instead of open(bookinfo.txt, "r")

zinc scarab
#

Huh?

#

Go print out filename

print(filename)
placid idol
#

i did

#

came up with .txt

#

so there is no filename

zinc scarab
#

Yeah

placid idol
# zinc scarab Huh?

like you know how when you are regulary opening files, you do open("filename.txt", "mode") as something:

zinc scarab
#

Yeah

placid idol
#

can i not do that?

zinc scarab
#

Yeah sure

#

Does the program always open the same file?

placid idol
#

yes

#

only file i have

zinc scarab
#

Yeah just pass the file name

#

Like a string

placid idol
#

because i did this in codeavengers and it seemed to work so i copypasted the code and changed it to my own stuff

#

but it didnt work here

zinc scarab
#

The prob is when you created the instance of your book you didn't specify a name

placid idol
#

yes

#

because my teacher said

#

it cannot be

#

hardcoded

zinc scarab
#

He said to pass all the params must be none?

placid idol
#

wait

#

can i paste my assesment code

zinc scarab
#

Go ahead

placid idol
#
class Book:

    def __init__(book, name, initavailbility = None ):
        book.name = name
        book.initialavailable = initavailbility
        book.borrowed_by = None
        book.borrow_date = None
        book.due_date = None
        book.isavailable = None  # Initialize as available when the book is created
    
    def __repr__(book):
       return f"book {book.name}"
    def __str__(book):
        return book.name
         
    def borrow_book_info(book, borrower, borrow_date, due_date):
        book.borrowed_by = borrower
        book.borrow_date = borrow_date
        book.due_date = due_date
        book.isavailable = False  
    def return_book_info(book):
        book.borrowed_by = None
        book.borrow_date = None
        book.due_date = None
        book.isavailable = True

    def bookinfotxtwrite(book,entryvargetter):

        with open("bookinfo.txt","a") as writebookfile:
           
           writebookfile.write(entryvargetter)
           

    def bookinfotxtread(book):
        # This method will read the file and create Book objects
            bookslist = []
            filename = book.name + ".txt"
            print(filename)
            with open(filename) as bi:
                line_list = bi.readlines()
                
                for line in line_list:
                     book_data = line.strip().split(",")

                     if len(book_data) == 2:  # If there are only 2 values in the file
                        book_data_inside = Book(book_data[0], None, None, None, book_data[1])
                        print(book_data_inside)

                     elif len(book_data) ==5:
                        book_data_inside = Book(*book_data)
                    

                

                    

#--------------------------------------------------------------------------------------------------------------------------------------------------


``` here
#

and

#


## bookstuff is the abbrivation for to kill a mocking bird
hi = Book("")
hi.bookinfotxtread()


bookslist = []

bookslist2 = []
booksavaliable  = [book for book in bookslist2 if book.isavailable]
booksnotavaliable = [book for book in bookslist2 if not book.isavailable]
#

so this is the code

#

i pasted it in parts becuse

#

tbh this is a short part

#

i just pasted the relavant bits

#

i have bad coding logic sorry

#

so do you know what i didnt add?

#

or what is wrong

#

i cant seem to figure it out

zinc scarab
#

what caused your programm to fail is this, take a look at thoss details,
first of all the init function py def __init__(book, name, initavailbility = None ): book.name = name here you initialized your variable and set self.name = name, BUT when you created the instance py book_data_inside = Book(book_data[0], None, None, None, book_data[1]) you passed none to name so now self.name = None

placid idol
#

oh

#

but book_data[1] is supposed be the name from file

#

i think

zinc scarab
#

is book_data a list?

placid idol
#

no the data from the bookinfo.txt

#

name and avalibility

zinc scarab
#

wait

#

why you don't pass self

#

did you wrote this code ?

placid idol
#

yes

#

i changed self to book because i realized self can be whatbver i want

placid idol
static gale
#

Well, this is true We conventionally call it self so that we're reminded that we're talking about some class instance.

zinc scarab
placid idol
#

yes

#

yeah bookinfoxtxtead(book) so it has the self as first param, just renamed book

zinc scarab
#

renamed

#

what

placid idol
#

like

#

self was just renamed into book

#

think of self but it is book

zinc scarab
zinc scarab
#

you can't just rename self on your own

placid idol
#

oh

#

so i just change back book to self?

zinc scarab
#

ofc

#

you don't rename language statments and expression and syntax

placid idol
#

oh

#

i changed it back

#

what do i do now

#

do i remove bookdatainside?

zinc scarab
placid idol
#

mostly

#

some were referenced from chatgpt

#

the reading part atleast

fossil badger
#

Could you use the paste service and share your current code, please?

#

!paste

barren pecanBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

placid idol
#

i just pasted

fossil badger
placid idol
#

oh ok

fossil badger
placid idol
#

no problem

#

only the part above

#
hi = Book("")
hi.bookinfotxtread()


bookslist = []

bookslist2 = []
booksavaliable  = [book for book in bookslist2 if book.isavailable]
booksnotavaliable = [book for book in bookslist2 if not book.isavailable]
 
``` is relavant right now though
static gale
zinc scarab
#

i'm not sure about this hi = Book("") hi.bookinfotxtread()

placid idol
zinc scarab
placid idol
#

since i dont know any valid ways of testing whether the code actually made the class or not

fossil badger
static gale
placid idol
fossil badger
placid idol
#

so it creates the class objects?

#

let me try rq

static gale
#

It creates an instance of the class.

#

(We make this distinction because the Book class itself is an object. Everything's an object.)

placid idol
#

oh

fossil badger
#

It seems you might be more familiar with Java, maybe?

placid idol
#

no

#

i have done some minor c++

#

but

#

that is all i know

fossil badger
#

I see. Some of the code style looked like it, why I asked.

placid idol
#

i just messed around with

#

i did the thing but hi is not defined

#

what do i put inside the bracket for

#

type

#

im sorry for asking all this lol i just dont get stuff sometimes

fossil badger
#

hi would not be defined if there's no hi = statement somewhere.
Where are you running the line for type()?

placid idol
#

outside function

fossil badger
#

And code runs in sequence, so this:

print(hi)
hi = Book()
``` is an error.
placid idol
#

oh

#

oh

#
['To Kill a Mockingbird', 'True']
['The Great Gatsby', 'True']
<class '__main__.Book'>
``` this s result
#

i know the file is being read but dont know if class is created with the name of the book or not

static gale
#

Well, the last line is from your print(type(hi))

#

You can print things from the instance. print(hi.name)

fossil badger
placid idol
#

oh

placid idol
fossil badger
#

Perhaps this will illuminate things:

one = Book("To Kill A Mockingbird")
two = Book("The Great Gatsby")

Play with these a bit. These are two instances of the same Book class.

placid idol
#
\anuro\OneDrive - Edgewater College\3TDIG\python stuff>                                                                                                             > & C:/Users/anuro/AppData/Local/Programs/Python/Python312/python.exe "c:/Users/anuro/OneDrive - Edgewater College/3TDIG/python stuff/2.5 borrow.py"

PS C:\Users\anuro\OneDrive - Edgewater College\3TDIG\python stuff> 

#

i just realized im doxxing my schools name lol

static gale
#

... andprobably your login name.

placid idol
#

oh

static gale
#

Anyway, you'd have to show us the contents of the 2.5 borrow.py file. ... and you did save it before running?

placid idol
#

yes it is saved

#

wait i ran the wrong file

static gale
#

Won't help ๐Ÿ™‚

placid idol
#

sorry

#

i changed some stuff

#

can i add them?

static gale
#

Don't understand what you mean here.

placid idol
static gale
#

Show away.

placid idol
#
class Book:

    def __init__(self, name, initavailbility = None ):
        self.name = name
        self.initialavailable = initavailbility
        self.borrowed_by = None
        self.borrow_date = None
        self.due_date = None
        self.isavailable = None  # Initialize as available when the self is created
    
    def __repr__(self):
       return f"self {self.name}"
    def __str__(self):
        return self.name
         
    def borrow_book_info(self, borrower, borrow_date, due_date):
        self.borrowed_by = borrower
        self.borrow_date = borrow_date
        self.due_date = due_date
        self.isavailable = False  
    def return_book_info(self):
        self.borrowed_by = None
        self.borrow_date = None
        self.due_date = None
        self.isavailable = True

    def bookinfotxtwrite(self,entryvargetter):

        with open("bookinfo.txt","a") as writebookfile:
           
           writebookfile.write(entryvargetter)
           

    def bookinfotxtread(self):
        # This method will read the file and create Book objects
            bookslist = []
        
            with open("bookinfo.txt", "r") as bi:
                line_list = bi.readlines()

                for line in line_list:
                    book_data = line.strip().split(",")
                    Book(*book_data)
          
#--------------------------------------------------------------------------------------------------------------------------------------------------
## bookstuff is the abbrivation for to kill a mocking bird
hi = Book("")
hi.bookinfotxtread()
print(type(hi))

bookslist = []

bookslist2 = []
booksavaliable  = [book for book in bookslist2 if book.isavailable]
booksnotavaliable = [book for book in bookslist2 if not book.isavailable]

#

i just backtracked

#

wait can you close this channel? ill probably come back later

#

asking for help

#

once i figured out some more stuff

static gale
#

You close it yourself by typing !close

placid idol
#

atp im hopeless on what to do and dont know what to do lol

#

oh ok

#

!close

barren pecanBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.