with open('file') as file_object: contents = file_object.read() print(contents)
fileand returns a file object that is saved in
withcloses the file when it is no longer needed. So, we don't need to warry about when to close the file.
readreads the contents of the file.
There is one difference between the output and the content of the file that is an extra blank line at the end.
read reaches the end of file it reads an empty string which appears as an extra blank line. To remove it
rstip as follows
with open('file') as file_object: contents = file_object.read() print(contents.rstip())
You can use a
for loop on the file object to examine each line from a file one at a time.
with open('file') as file_object: for line in file_object: print(line)
The file_object scope
file_object returned by
open is only available inside the
with block. To access a file's contents outside the
with block you need to store it in a variable (i.e. list). For example
with open('file') as file_object: lines = file_object.readlines() for l in lines: print(l.rstrip())
When Python reads from a text file, it interprets all text in the file as a string. If you read in a number and want to work with that value in a numerical context, you'll have to convert it to either an integer using the
int() function or a float using the
To write to a file you need to open it in write mode by adding the second argument
w to the
Then you can write to the file by calling the
write() method on the file object as follows
with open('file', 'w') as file_object: file_object.write("I love learning \nPython in paticular is my favorite")
In Python you can open a file in:
Opening a file in write mode will create it if it is not exist or erase it otherwise.
To continue writing on the next line you need to add
\n (newline) to the string