









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Read data from file into python variables. File ... print(s). Out[1]: String with newline. String with newline. ... or remove the "\n" using .rstrip():.
Typology: Study notes
1 / 16
This page cannot be seen from the preview
Don't miss anything!










file_handle = open("file.txt", "r") # open in 'r' mode contents = file_handle.read() # reads the entire file file_handle.close() # always close at the end
file_handle = open("file.txt", "w") # open in 'w' mode
file_handle.write("New file contents.\n") file_handle.close() # always close at the end
In [1]: s = "String with newline.\n"
print(s) print(s) Out[1]: String with newline. String with newline.
In [1]: s = "String with newline.\n"
print(s, end='') print(s, end='') Out[1]: String with newline. String with newline.
In [1]: s = "String with newline.\n"
print(s.rstrip(), end='') print(s.rstrip(), end='') Out[1]: String with newline.String with newline.
Unlike print(), the .write() function does not add a "\n".
file_handle = open("file.txt", "r") contents = file_handle.read() file_handle.close()
with open("file.txt", "r") as file_handle: contents = file_handle.read()