









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
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
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!
open()
function opens the filefile_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
open()
function opens the filefile_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"
end
to suppress 2nd "\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".
contents
now holds thelines
now holds a list offile_handle = open("file.txt", "r") contents = file_handle.read() file_handle.close()
with
with open("file.txt", "r") as file_handle: contents = file_handle.read()