Bootstrap FreeKB - Python (Scripting) - Read a file (open)
Python (Scripting) - Read a file (open)

Updated:   |  Python (Scripting) articles

open can be used to open a file for reading or writing. The second parameter can be:

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.

#!/usr/bin/python

with open("/tmp/hello.txt", "r") as file:
  print(file.read())
file.close()

 

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:

#!/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 Buy Me A Coffee



Comments


Add a Comment


Please enter ef2854 in the box below so that we can be sure you are a human.