Whats wrong with my code? file.write() and file.read()


#1

#need ya help guyz
#i can start and read out the file totally fine
#when i add some "products" to my list, it works but if i want to read the files content it says following:
"""
Welcome to your personal shop assistant!
Press any button to start.d
Do you want to add a new item or read out your list? ("ADD"/"READ"/"EXIT")ADD
What would you like to add?bla
You successfully added bla to your shopping list!
What's up next? ("ADD"/"READ"/"EXIT")ADD
What would you like to add?blabla
You successfully added blabla to your shopping list!
What's up next? ("ADD"/"READ"/"EXIT")READ
Traceback (most recent call last):
  File "C:/Users/julia/PycharmProjects/shoppingaid/script.py", line 51, in <module>
    program(welcomeMessage)
  File "C:/Users/julia/PycharmProjects/shoppingaid/script.py", line 37, in program
    program(additionMessage)                 #let the user do more
  File "C:/Users/julia/PycharmProjects/shoppingaid/script.py", line 37, in program
    program(additionMessage)                 #let the user do more
  File "C:/Users/julia/PycharmProjects/shoppingaid/script.py", line 39, in program
    print "Your shopping list currently includes:", shoppinglist.read()     #print file.read()
  File "C:\Python27\lib\codecs.py", line 686, in read
    return self.reader.read(size)
  File "C:\Python27\lib\codecs.py", line 492, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf8 in position 261: invalid start byte
Your shopping list currently includes:

Process finished with exit code 1

"""

#my shoppinglist.txt file then looks something like this:

#bla
#blabla
#t.close()
# )
# ssage)
#  I believe in you!
# itten let user try again
# ()
# nt file.read()
#
# wing:
#
#_ ���pu�n27\lib\site.pyc


#  i figured my program has a problem at the end of writing content but i cant quite figure out what it is...


import codecs

#  codecs because i had an error depending the file encoding

shoppinglist = codecs.open("shoppinglist.txt", "r+", "utf-8")

#  friendly hello

print "Welcome to your personal shop assistant!"
raw_input("Press any button to start.")

#  what the program can ask you

welcomeMessage = "Do you want to add a new item or read out your list? (\"ADD\"/\"READ\"/\"EXIT\")"
additionMessage = "What's up next? (\"ADD\"/\"READ\"/\"EXIT\")"
readMessage = "Got everything? (\"ADD\"/\"READ\"/\"EXIT\")"

#  program as a function to be able to let the user change his list more

def program(message):
    case = raw_input(message)      #asking him what to do
    if case == "ADD":                       #if he wants to add something
       addition= str(raw_input("What would you like to add?"))       #enter what to add in str
       shoppinglist.write(addition)                 #  append addition to the file
       shoppinglist.write("\n")                     #new line
       print "You successfully added", addition, "to your shopping list!"   #printing what was added
       program(additionMessage)                 #let the user do more
    elif case == "READ":                     #if he wants to just read the file
        print "Your shopping list currently includes:", shoppinglist.read()     #print file.read()
        program(readMessage)                    #let the user do more
    elif case == "EXIT":                    #if the user has finished his list
      print "See ya! This is your list:", shoppinglist.read()   #print file.read()
      print "exiting..."
      exit()            #exiting the program
    else:               #in case something else was written let user try again
        print "You can try again, I believe in you!"
        program(welcomeMessage)

#  starting the program

program(welcomeMessage)

#  closing the file

shoppinglist.close()

#2

Some possibilities:

  • Your program writes garbage
  • Your program doesn't read garbage
  • Your program doesn't read well-formed input

Can you think of ways to test which it is?


#3

it writes such garbage that it cant read this ■■■■ anymore, it writes these signs up top there. figured that out but how to fix it?


#4

Have you ruled out the possibility that the garbage is there since from before your program wrote anything to it?

If you clear the file, what input do you use to get your program to write garbage?


#5

i tried the case someone opened it and exited it again so it only writes something to the file in case someone wants to ADD a product...


#6

oh btw if i clear it completely and write it i can read it out perfectly

just in case thered already some content inside this error comes up


#7

So it doesn't write garbage, and it also doesn't manage to make sense out of something that doesn't contain sense.

There's no problem then, right?


#8

there is still the same problem i posted here, i asked for help


Gesendet mit der
Telekom Mail App

--- Original-Nachricht ---

Von: Jonatan

Betreff: [Codecademy Discuss] [Python/21. File Input/Output] Whats wrong with my code? file.write() and file.read()

Datum: 05.04.2017, 3:59 Uhr

An: julian.muenzer@gmail.com

#006699;; font-size:13px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;color:#3b5998;text-decoration:none;font-weight:bold">ionatanI'm a train. A red one.

April 5

#e9e9e9; background-color: #f8f8f8; margin: 0;; padding: 12px 25px 2px 12px; margin-bottom: 10px;">
boardpro87002:

oh btw if i clear it completely and write it i can read it out perfectly

just in case thered already some content inside this error comes up

So it doesn't write garbage, and it also doesn't manage to make sense out of something that doesn't contain sense.

There's no problem then, right?



Visit Topic or reply to this email to respond.



In Reply To


boardpro87002

April 4oh btw if i clear it completely and write it i can read it out perfectly just in case thered already some content inside this error comes up


#ddd; height: 1px; border: 1px;; background-color: #ddd; height: 1px; border: 1px;">

#006699;; color:#666;" target="_top">Visit Topic or reply to this email to respond.

To unsubscribe from these emails, click here.



#9

To recap

First the problem was reading some file, though the file content is unknown (you posted some text but it was not a byte-for-byte copy of the file and therefore doesn't reproduce what you decribed), but presumed to be garbage. If the file has garbage in it, then the problem is the file, not the program.

Then, you said your program writes garbage. However, you did not explain how to make it do that, I suspect it doesn't and that you just took a wild guess.

Then you said it writes and reads just fine. And that it doesn't read garbage, but that's impossible anyway so it doesn't matter, it's garbage, you don't want to read it. Remove the garbage instead.

So to me it looks like the problem was that you used an invalid file. That would kind of be like using a broken computer and question why a program isn't running - the problem is with the computer (file) not the program. (If my guess is correct, which I don't know)

If there's still a problem, then I'm unable to understand what it is. What it would take for me to understand the problem is a way of reproducing it, along with a description of what happens differently from what should happen


#10

i wrote it several times already...the reading works properly. if the file is empty the writing does too. just in case there is content in the file on the start it writes garbage. and this garbage cant be read out anymore


#11

Can't reproduce.

Tell me what to type, starting from an empty file

Your file is probably not empty, or another program is also writing to it.


#12

type
d
ADD
cheese
READ

then you get the error
null


#13

nate@laptop → truncate --size 0 shoppinglist.txt
nate@laptop → python2 blah.py 
Welcome to your personal shop assistant!
Press any button to start.d
Do you want to add a new item or read out your list? ("ADD"/"READ"/"EXIT")ADD
What would you like to add?cheese
You successfully added cheese to your shopping list!
What's up next? ("ADD"/"READ"/"EXIT")READ
Your shopping list currently includes:
Got everything? ("ADD"/"READ"/"EXIT")EXIT
See ya! This is your list:
exiting...

That doesn't reproduce it. I still think you're not emptying your file first.

You can write a python script to empty it:

open('shoppinglist.txt', 'w')

(yeah just that)


#15

If I'm right, then adding that line at the top of your code will have the effect that your code no longer crashes.

Actually, close the file as well, so instead use:

open('shoppinglist.txt', 'w').close()


#16

if i open it in writing mode i can write but not read it. and in my case i want to let thr user do both...and i do close the file at the end of code
null


#17

Right, but I just want you to open the file in write mode and then immediately close it again. Then you can re-open it with codecs.

The reason for doing that is that the file will be emptied, which I don't think you've done


#18

I'm actually pretty certain that your file isn't empty, aside from the guesswork.

Because if you start with an empty file, write some to it, then read the rest - then you will read zero bytes, because the file position is going to be at the end of the file, not at the top.


#19

yo dude, i dont want to empty it, this would delete data the user would use...

null


#20

If it's garbage then yes, you do


#21

I'm not suggesting that the final program should empty the file on startup. However, everything suggests that you still haven't cleared the file, which that code accomplishes.

I'd love it if you came up with a way I can reproduce what you describe - but as you see from the output I posted above, truncating the file to 0 bytes and then running your program with the input you suggested, that did not crash it.