1. About a Python files

Until now, the programs we have carried out have only processed a very small number of data. We could therefore each time include this data in the body of the program itself(for example in a list). However, this way of proceeding becomes completely inadequate when one wishes to process a larger quantity of information. Hence the justification for using the files.

2. File open mode

In Python language, there is no need to import a library to read and write files. These are operations managed natively in  language. The first thing to do is to use Python's built-in open() function to get a Pyhon file object. The open() function opens a file in a fairly simple way! When you use the open() function, it returns an object of file object type. File object contain methods and attributes that can be used to collect informations about the file you have opened. They can also be used to manipulate the said file. A file object created by the open() method, has certain properties allowing to read and write in a file. Its syntax is:

f = open([file name], [open mode])

The [file name] is the name of the file you want to open or create. The opening mode includes the following parameters:

  1. 'r' mode: opening an existing file in read-only mode,
  2. The 'w' mode: open for writing only, overwritten if it already exists and creates if it does not exist,
  3. 'a' mode: opening and writing at the end of the file with conservation of existing content
  4. '+' mode: open in read and write
  5. 'b' mode: opening in binary mode

3. Opening and reading a file

To read an existing file, several methods are available: 3.1. Full read with the read() method The read() method allows you to read the total or partial content of a file, after being opened with the open() method. The syntax is:

file.read()

Example. open and read an existing file

f = open("myFile.txt", 'r')
content = f.read() # reading content
print(content) # print content
f.close() # closing the file

3.2. Partial reading with the read() method

The read() method can also be used to read part of the file only by indicating the number of characters to read in parentheses: Example. read the first 20 characters

f = open("myFile.txt", 'r')
content = f.read(20) # read 20 characters from file content
print(content) # print content
f.close() # closing the file

Note After executing the read(n) function(n = number of characters to read), the cursor is at position n + 1, and therefore if you execute the function a 2nd time, reading will start from(n + 1 ) th character.

3.3. Sequential reading character by character

The read() method can also be used to perform a sequential reading character by character using the for loop:

for c in file.read()

Example: of sequential read

f = open("myFile.txt", 'r')
s = ""
for c in f.read():
    s = s + c
print(s)

The same operation can be performed using the while loop: Example. reading a file with the while loop

f = open("myFile.txt", 'r')
s = ""
while 1:
    c = f.read(1)
    if c == "":
        break
    s = s + c
print(s)

3.4. Reading line by line with the readline() and readlines() methods

3.4.1. The readline() method

The readline() method allows you to read a file line by line. This method points to the first line when it is executed for the first time, then to the second line when it is executed for the second time and so on the n-th execution it points to the n-th line. Example. read the file line by line

f = open("myFile.txt", 'r')
print(f.readline()) # print line n ° 1
print(f.readline()) # print line n ° 2

By combining the readline() method with the while() method, you can read all of the lines in a file:

Example. read all lines with readline()

f = open("myFile.txt", 'r')
s = ""
while 1:
    line = f.readline()
    if(line == ""):
      break
    s = s + line
print(s) # printing all lines

3.4.2. The readlines() method

The readlines() method, returns a list whose elements are the lines of the file Example. read lines from file with readlines()

f = open("myFile.txt", 'r')
content = f.readlines()
print(content [0]) # printing the first line
print(content [1]) # print the second line




Note:

You can also read all the lines of the file by applying the for loop: Example. read lines using the for loop

f = open("myFile.txt", 'r')
content = f.readlines()
for line in content:
    print(line)

We can therefore, via readlines(), retrieve the number of lines in a file by applying the len() method:

Example. number of lines in a file

f = open("myFile.txt", 'r')
content = f.readlines()
line_number = len(content) # retrieving the number of lines in the file

By retrieving the number of lines in a file, we can therefore read all of its lines using the for loop:

Example. read all the lines with the for loop

f = open("myFile.txt", 'r')
content = f.readlines()
n = len(content)
for i in range(0, n):
    print(content [i])

3.4.3. Reading a file at a specific position with the readlines() method

The readlines() method also allows us to read a file at a specific position: Example. reading a file from character 10 to character 20 of the third line

f = open("myFile.txt", 'r')
content = f.readlines() [2] # retrieving the second line
result = content [9:19] # extract from the character at position 10 to 20
print(result)

3.4.4. Reading from a given position using the seek() method

The seek() method allows you to select a precise position for reading or writing. Example. read the file from the 6 th position

f = open("myFile.txt", 'r')
f.seek(5) # selection of position 5
print(f.read()) #read the file from the 6 th position
Younes Derfoufi
my-courses.net

Leave a Reply