Note 11.3.2.
A common error that novice programmers make is not realizing that all these ways of reading the file contents, use up the file. After you call readlines(), if you call it again you’ll get an empty list.
read()
method returns the entire contents of the file as a single string (or just some characters) if you provide a number as an input parameter. The readlines
method returns the entire contents of the entire file as a list of strings, where each item in the list is one line of the file. The readline
method reads one line from the file and returns it as a string. The strings returned by readlines
or readline
will contain the newline character at the end. The following table summarizes these methods and the following session shows them in action.Method Name | Use | Explanation |
---|---|---|
read(n) |
filevar.read() |
Read and return a string of n characters, or the entire file as a single string if n is not provided. |
readline() |
filevar.readline() |
Read and return the next line of the file with all text up to and including the newline character. |
readlines() |
filevar.readlines() |
Returns a list of strings, each representing a single line of the file. |
readlines()
with a for loop, or use read()
to get all of the contents as a single string.while
loop. Fortunately, you don’t need to learn this other pattern, and we will put off consideration of while
loops until later in this course. We don’t need them for handling data from files.school_prompt2.txt
(shown below), find the number of characters in the file and assign that value to the variable num_char
.travel_plans2.txt
(shown below), and assign it to the variable num_lines
.Writing essays for school can be difficult but many students find that by researching their topic that they have more to say and are better informed. Here are the university we require many undergraduate students to take a first year writing requirement so that they can have a solid foundation for their writing skills. This comes in handy for many students. Different schools have different requirements, but everyone uses writing at some point in their academic career, be it essays, research papers, technical write ups, or scripts.
This summer I will be travelling. I will go to... Italy: Rome Greece: Athens England: London, Manchester France: Paris, Nice, Lyon Spain: Madrid, Barcelona, Granada Austria: Vienna I will probably not even want to come back! However, I wonder how I will get by with all the different languages. I only know English!