How to Read a File in Python
Python hosting: Host, run, and code Python in the cloud!
You have seen various types of data holders before: integers, strings, lists. But so far, we have not discussed how to read or write files.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Read file
The Python programming language provides the ability to work with files using open()
.
Python programming treats some files as text files, where lines are separated by newline characters \n
. You can open regular files with the paramater r
.
Other files are considered binary and can be handled in a way that is similar to the C programming language. They need to be opened with the parameters rb
.
read file into string
This is a sample program that shows how to read data from a file.
The file needs to be in the same directory as the program, if not you need to specify a path.
Create python script. Open editor of your choice and create new python script. Then paste the following code.
f = open("file.txt","r") |
The read method readlines()
reads all the contents of a file into a string.
Save the file with name example.py and run it.
read file line by line
To output line by line, you can use a for loop. The lines may include a new line character \n
, that is why you can output using endl=""
.
f = open("filename.txt","r") |
Another option is to remove the newline characters with the replace() method.
f = open("test.py","r") |
read file with keyword
The with keyword can be used to read files too. This automatically closes your file.
#!/usr/bin/env python |
The first part of the code will read the file content. All of the lines read will be stored in the variable content. The second part will iterate over every line in the variable contents.
If you do not want to read the newline characters ‘\n’, you can change the statement f.readlines() to this:
content = f.read().splitlines() |
Resulting in this code:
#!/usr/bin/env python |
While the codes above work, we should always test if the file we want to open exists. We will test first if the file does not exist, if it does it will read the file else return an error. As in the code below:
#!/usr/bin/env python |
If you are new to Python programming, I highly recommend this book.
Leave a Reply:
So what is the writing mode for r+ ?
Hi Stan, r+ opens the file for both reading and writing from the start of the file.
and w+ appends the data to existing file, I suppose.
w+ opens for reading and writing. The file is created if it does not exist, otherwise it is truncated (data is deleted if exists). The stream is positioned at the beginning of the file. Use a+ if you want to append
How to open a html file in a navigator from Python??
Hi Jahir, what do you mean by navigator? Do you mean a webbrowser?
If you want to parse HTML look at this tutorial: https://pythonspot.com/http-parse-html-and-xhtml/.
If you want a webbrowser to open an html file in your webbrowser, simply execute it as program: https://pythonspot.com/python-subprocess/
"The first part of the code will read the file contents and the second part will that line by line."
Typo? I don't understand this sentence.
Thanks Christian! Yes, this is a typo. I updated it
Two questions:
For the python3 replacement of the command, "print line," is it "print(line,)" or "print(line)," ?
Shouldn't the file in the "Read" example, also be closed with the command, "f.close()", or is the file automatically closed at the end of a program if it is opened with the command, "with open(filename) as f"? (Still it seems risky to leave it open longer than necessary, in case the program crashes at some later point.)
Hi Ian!
For python3, use print(line) because print is a function. The comma between the brackets is used for tuples.
Using "with open(filename) as f" the file will automatically be closed after the block of code has completed.
Hi Frank!
What's the differences between with open and open?Can I use with open as f:f.write("blah blah")?Thanks!
The with statement executes all code in the block and closes the file automatically. File manipulations can be done inside the code block using with. If you use open you can do file operations at any time until you close the file.
Nice tuts, thanks for this.