Python Forum

Full Version: How to read a file into a variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.