Sunday 24 November 2013

How to open text file in Python

Example 1
This example done on simple text file "test.txt" having content as per following:

x
y
z

Do following in Python Shell in order to read file content:

>>> # open the file in a read mode
>>> f = open (r"C:\opt\test.txt")
>>> # once file is open, read all the lines
>>> f.readlines()

...and as a result you get list with items representing lines in the text file.

>>>
['x\n', 'y\n', 'z']
>>>

Note: 
Characters "\n" represent end of the line. In order to remove it, use function "rstrip("\n")".




Example 2
This example is done in the same file as in Example 1, let's try another option, which is reading line by line via for loop:

...in Python Shell:

>>> f = "C:\opt\test.txt"
>>> #
>>> # open the file in a read mode
>>> f_open = open(file, 'r')
>>> #
>>> # and read line by line
>>> for lines in f_open:
      # remove end characters "\n" on each line
      lines = lines.rstrip("\n")
      print(lines)

Results are as following (this time not a list):

>>>
x
y
z
>>>

No comments:

Post a Comment