Python Forum

Full Version: Can we store value in file if we open file in read mode?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Using the open() function, open the test.txt file in reading mode and store it in the variable called file_2

Is this possible to create variable when we open a file in read mode?
Yes you can always create variables.
(Sep-26-2020, 07:51 AM)ibreeden Wrote: [ -> ]Yes you can always create variables.

Hi Could you please explain the syntax how to do it ? as I tried with below syntax but no successes
file = open('test.txt', 'r')
file.write('file_2')
Please read 7.2. Reading and Writing Files and open(). You opened the file for reading, so you cannot write to it. If you want to write to a file you must open it for writing ("w") or appending ("a") or read-write ("+").
file = open('test.txt', 'w')
file.write('file_2')