Python Forum
How to read a file into a variable - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to read a file into a variable (/thread-5611.html)



How to read a file into a variable - hello_its_me - Oct-13-2017

hi everyone, I am searching for a solution to read a number or a word into a variable out of a file and the other way round so to write a variable into a file. I found way too many things and wanted to know something that works 100%.

Thanks


RE: How to read a file into a variable - buran - Oct-13-2017

https://python-forum.io/Thread-Basic-Files


RE: How to read a file into a variable - wavic - Oct-13-2017

Open a file and read it.
with open('file.txt', 'r') as f:
    words = f.read() # all file data will be into 'words'
Open a file for writing:
with open('file.txt', 'w') as f:
    f.write(words) # write the data into the file
Both operations will close the file after the with code block ends.