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 Course: Complete Python Programming Course & Exercises

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:

 #!/usr/bin/env python

filename = "readme.txt"

with open(filename) as fn:
content = fn.readlines()

print(content)

Content will contain a list of all strings in the file.

python read file

If you print the variable content:

print(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:
content = [x.strip() for x in content]

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.

#!/usr/bin/env python

filename = "x.py"
contents = open(filename,'r').read()
print(contents)

Download exercises