Read File

Reading files is straightforward: Python has built in support for reading and writing files. The function readlines() can be used to read the entire files contents.

Related Courses

Read file into list

We call the function method open to read the file, then we call the method readlines() to read all of the file contents into a variable. Finally we print out all file data.

Example read file:

Content will contain a list of all strings in the file.
If you print the variable content:

you would see a list. Every item of the list contains one line. However, every line of the list contains the newline character (\n).

To remove the newline characters from the list use:

Read file into string

If you want to read a file into a string variable, you can use a different method.
The code below reads the entire file data into a single string.

Previous Post
Next Post

15 Replies to “Read File”

  1. When I launch this, I receive following error message:

    $ python read_file.py
    File “read_file.py”, line 3
    with open(filename) as fn:
    ^
    SyntaxError: invalid syntax

    Can it be related with the Python version?
    I have 2.4.3

  2. It might be nice to include an explanation of “with” in this part. I had to look it up, and it appears to be a generalization of the ‘for’ statement that is unique to Python.

    From what I’ve seen, these are tutorials for experienced programmers as to the differences between Python and other languages and while a long drawn out explanation would defeat the purpose of brevity, a short sentence explaining the reason for using ‘with’ and contrasting with ‘for’ should suffice.

    While I’m typing, I also would like to say how much I appreciate these tutorials, they are exactly what I needed and HOLY CRAP DO I LOVE PYTHON IT IS SO AWESOME.

Leave a Reply

Your email address will not be published. Required fields are marked *