0

I am a beginning python user and have come upon a dilemma. My program is supposed to read and write in a specific file. While the write function works, the read function simply erases all text from the file.

def main():
r = open('C:\\Users\\AM\\Desktop\\cool.txt', 'r')
w = open('C:\\Users\\AM\\Desktop\\cool.txt', 'w')
answer = input('Would you like to read or write? (To leave say "quit")')
if(answer == 'read'):
    if(r.mode == 'r'):
        contents = r.read()
        print(contents)
elif(answer == 'write'):
    w.write(input('What would you like to write?'))
    w.close()
elif(answer == 'quit'):
    quit()
else:
    print('Sorry, I do not understand')
main()

Thank you for your time!

6
  • 1
    I would recommend not opening the file till they ask to read or write, just for the sake of not having both open at the same times Commented Aug 17, 2017 at 17:16
  • 3
    Please indent your code properly. Whitespace is essential in Python. Commented Aug 17, 2017 at 17:16
  • 4
    Well... don't open your file in write mode, then?
    – cs95
    Commented Aug 17, 2017 at 17:16
  • 3
    It's not read fault. It's that line w = open('C:\\Users\\AM\\Desktop\\cool.txt', 'w') Opening a file in write mode clears it. You need to specify that you want to append to it when openning
    – litelite
    Commented Aug 17, 2017 at 17:16
  • 1
    It's really not a good idea to open more than one file handle at a time on a file, things can get messy.
    – PM 2Ring
    Commented Aug 17, 2017 at 17:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.