Open a File on the Server
Assume we have the following file, located in the same folder as Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open[]
function.
The open[]
function returns a file object, which has a read[]
method for reading the content of the file:
Example
f = open["demofile.txt",
"r"]
print[f.read[]]
Run Example »
If the file is located in a different location, you will have to specify the file path, like this:
Example
Open a file on a different location:
f = open["D:\\myfiles\welcome.txt", "r"]
print[f.read[]]
Run Example »
Read Only Parts of the File
By default the read[]
method returns the whole text, but you can also specify how many characters you want to return:
Example
Return the 5 first characters of the file:
f = open["demofile.txt", "r"]
print[f.read[5]]
Run Example »
Read Lines
You can
return one line by using the readline[]
method:
Example
Read one line of the file:
f = open["demofile.txt", "r"]
print[f.readline[]]
Run Example »
By calling readline[]
two times, you can read the two first lines:
Example
Read two lines of the file:
f = open["demofile.txt",
"r"]
print[f.readline[]]
print[f.readline[]]
Run Example »
By looping through the lines of the file, you can read the whole file, line by line:
Example
Loop through the file line by line:
f = open["demofile.txt", "r"]
for x in f:
print[x]
Run Example »
Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finish with it:
f = open["demofile.txt", "r"]
print[f.readline[]]
f.close[]
Run Example »
Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.
How to read and print the content of a txt file
Assume you got a file called file.txt that you want to read in a program and the content is this:
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip[], you avoid printing
an empty line between each [not empty] line
You can read this content: write the following script in notepad:
with open["file.txt", "r", encoding="utf-8"] as file:
for line in file:
print[line.strip[]]
save it as readfile.py for example, in the same folder of the txt file.
Then you run it [shift + right click of the mouse and select the prompt from the contextual menu] writing in the prompt:
C:\examples> python readfile.py
You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file [4 spaces are good].
output
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip[], you avoid printing
an empty line between each [not empty] line
Problem Formulation
Given the path to a text file such as /path/to/file.txt
.
How to read all the content from the file and print it to the Python standard output?
Standard File Reading and Printing
The standard approach to read the contents from a file and print them to the standard output works in four steps:
- Open the file.
- Read the content.
- Print the content.
- Close the file.
Let’s dive into each of those four steps next.
Here’s how this whole process looks like on my computer:
Step 1: Open the file for reading using the built-in open[]
function with the text file path as the first string argument and the reading mode 'r'
as the second argument. Assign the resulting file object to a variable [e.g., named f
].
f = open['/path/to/file.txt', 'r']
Step 2: Read the whole textual content from the
file using the file.read[]
method and store it in a variable [e.g., named content
]. If your file consists of multiple lines, the resulting string will contain newline characters '\n'
for each line break.
content = f.read[]
Step 3: Print the file content by passing the content variable into the built-in print[]
function.
print[content]
Step 4: Close the file to clean up your code. This is a good practice according to the Python standard.
f.close[]
Taken together, the proper code to read the contents of a text file and print it to the standard output looks like this:
f = open['/path/to/file.txt', 'r'] content = f.read[] print[content] f.close[]
Please note that you need to replace the string '/path/to/file.txt'
with your own path
to the file you want to read.
Do you need some more background? No problem, watch my in-depth tutorial about Python’s open[]
function:
Python open[] Function – An 80/20 Guide by Example
How to Read all Lines of a File into a List [One-Liner]?
You can also read all lines of a file into a list using only a single line of code:
print[[line.strip[] for line in open["file.txt"]]]
To learn how this works, visit my in-depth blog article or watch the following video tutorial:
Python One-Liners - Trick 2 Read File and Strip[] Lines
How to Read a File Line-By-Line and Store Into a List?
A more conservative, and more readable approach of achieving this is given in the following code snippet:
with open['file.txt'] as f: content = f.readlines[] # Remove whitespace characters like '\n' at the end of each line lines = [x.strip[] for x in content] print[lines]
You can see this in action in this blog tutorial and the following video guide:
How to Read a File Line By Line and Store Into a List
Hey, you’ve read over the whole article—I hope you learned something today! To make sure your learning habit stays intact, why not download some Python cheat sheets and join our free email academy with lots of free Python tutorials?
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.