0

I am messing around with some code to learn how to use the write and read method. So far I opened up a file called output.txt and stripped the whole line and also the last character of the line. Then I lower case all the characters that are in the output.txt. I am having trouble adding the content from variable lc to output.txt without deleting what is already in the output.txt. I tried f.write(lc) , but got an error (io.UnsupportedOperation: not readable)

Here is the code that I have so far

# open file using "with"
with open("output.txt",'w') as f:
    lines = f.read()
    
    # strip the newline and the last character from what is read in
    newLine = lines.strip()
    lastChar = lines.strip()[len(lines) - 1]

    # convert the text to lower case
    lc = newLine.lower()

    # print the lower-case text and a newline to standard output
    f.write(lc) 
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

you can't read from file using w mode , with'r+' mode, using write method will write the string object to the file based on where the pointer is.

# open file using "with"
with open("output.txt",'r+') as f:
    lines = f.read()
    
    # strip the newline and the last character from what is read in
    newLine = lines.strip()
    lastChar = lines.strip()[len(lines) - 1]

    # convert the text to lower case
    lc = newLine.lower()

    # print the lower-case text and a newline to standard output
    f.write(lc) 
Belhadjer Samir
  • 1,461
  • 7
  • 15