3 steps to reading text files in python | applied electronics engineering


3 steps to reading text files in python

By Applied Electronics - Thursday, July 28, 2016 No Comments
Steps to read a text file such as data.txt using python programming language is as follows.

1. create a file object
fobj = open("data.txt",'r')

where the first argument in the function open is the filename(which can also be a path to the filename) and the second argument is the file operation which is r which means read.

2A. read the file content line by line

There are different ways to do this.

a. using readline( ) function

datatxt = fobj.readline( )

Note 1: datatxt is a file object now and holds strings data type. So if you were to read numeric values form the files you have to convert it to interger or float.

Note 2: readline( ) reads one line at a time as opposed to read( )(see below)

b. using for loop

datatxt = [ ]
for j in fobj:

c. using list comprehension

datatxt = [j for j in fobj]

d. using while loop

while true:
      datatxt = fobj.readline( )
      if not datatxt:

2B. read the whole content of the file

using read( )

fobj = open('data.txt', 'r')
datatxt = fobj.read( )

read( ) reads the whole content of the text file and stores the content as string.

3. close the file object

fobj.close( )

flushes the memory held by the file object.

The above method is very similar to reading files in C programming language.

There are other ways to read files in python. For example, numpy package, panda package have different methods to read files.

No Comment to " 3 steps to reading text files in python "