
open can be used to open a file for reading or writing. The second parameter can be:
- a = append to the file
- r = read the file
- w = write (overwrite) to the file
Let's say /tmp/hello.txt contains the following.
Hello World
Here is how you can open the file for reading.
#!/usr/bin/python
file = open("/tmp/hello.txt", "r")
print(file.read())
file.close()
Or like this. When using with open the file is automatically closed once you are no longer within the with open block thus there is no need to have something like file.close().
#!/usr/bin/python
with open("/tmp/hello.txt", "r") as file:
print(file.read())
Which should print the content of the file.
~]$ python example.py
Hello World
Let's say the file contains empty new lines.You can try using strip or rstrip to remove the empty new lines.
#!/usr/bin/python
file = open("/tmp/hello.txt", "r")
print(file.read().strip())
file.close()
Typically, it is a good idea to:
- use os.path.exists to determine if the file exists
- use os.path.isfile to determine if the file is a file (not a directory)
- use os.access to determine if the file is readable or writable
#!/usr/bin/python
import os
target_file = "/tmp/hello.txt"
if os.path.exists(target_file) and os.path.isfile(target_file) and os.access(target_file, os.R_OK):
file = open(target_file, "r")
print(file.read())
file.close()
You can loop through each line in the file.
file = open("/tmp/hello.txt", "r")
for line in file:
print(line)
file.close()
Or like this.
with open("/tmp/hello.txt", "r") as file:
for line in file:
print(line)
readlines and splitlines can be used to store each line in the file as an element in a list. For example, let's say /tmp/lines.txt contains the following.
Line one
Line two
readlines will store the lines in the files as elements in a list with trailing \n (new lines).
#!/usr/bin/python
file = open("/tmp/lines.txt", "r")
print(file.readlines())
file.close()
Which should return the following.
['Line one\n', 'Line two\n']
splitlines will also store the lines in the files as elements in a list but without the trailing \n (new line).
#!/usr/bin/python
file = open("/tmp/lines.txt", "r")
print(file.read().splitlines())
file.close()
Which should return the following.
['Line one', 'Line two']
Since readlines will include the trailing \n (new lines), if you loop over the elements . . .
file = open("lines.txt", "r")
for line in file.readlines():
print(line)
file.close()
For lines that end with the trailing \n (new line), the output may include empty new lines.
Line one
Line two
Since splitlines does not include the trailing \n (new lines), if you loop over the lines in the file . . .
file = open("lines.txt", "r")
for line in file.read().splitlines():
print(line)
file.close()
Or like this.
with open("lines.txt", "r") as file:
for line in file.read().splitlines():
print(line)
There should be no empty new lines.
Line one
Line two
Did you find this article helpful?
If so, consider buying me a coffee over at