0

I am trying to learn how to open txt.files on Python 3.7. I have a file (Days.txt) with the following content:

Monday Tuesday Wednesday Thursday Friday Saturday Sunday

On Jupyter, I used the following code:

f = open('Days.txt','r').read()
f

which gave me the following result:

'Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday'

so far, so good.

Then, I tried to add a sentence to the Days.txt file by:

f.write('this is a test\n')

and that's where I get the below error message:

AttributeError Traceback (most recent call last) in ----> 1 f.write('this is a test\n')

AttributeError: 'str' object has no attribute 'write'

Why isn't it working?

The code below results in another error message:

file = open('Days.txt','r')
s = file.read()
file.write('this is a test\n')
file.close()

---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-138-0cc4cd12a8b3> in <module>
      1 file = open('Days.txt','r')
      2 s = file.read()
----> 3 file.write('this is a test\n')
      4 file.close()

UnsupportedOperation: not writable
1
  • 1
    It shows that f is actually a string. Before trying to write, check type(f). Also, when reading files it is a good practice doing it inside a with clause, like with open(days.txt) as f: ..... And finally when appending things to the end of file you need to specify the 'a' parameter, like f.write('text', 'a') Commented Jul 15, 2021 at 13:45

2 Answers 2

1

Because f is a string, not the file pointer, it's better to keep the file pointer in its own variable:

f = open('Days.txt', 'r')

s = f.read() # <-- check the content if you need it
print(s)

f.write('this is a test\n')

f.close() # <-- remember to close the file

Better yet to automatically close the file:

with open('Days.txt', 'r') as f:
    s = f.read()
    print(s)
    
    f.write('this is a test\n')
Sign up to request clarification or add additional context in comments.

Comments

0

Open the file in write mode to allow adding new contents to it. To do so, just

f = open("Days.txt", "a")
f.write("This is a text\n")
f.close()

Remember to close the file handler after opening it. I however suggest you to use the "with" construct, that automatically closes the file handler after the read/write operation

with open("Days.txt", "a") as f:
    f.write("This is a text\n")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.