Social Icons

Sunday, March 1, 2020

Python Files

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:

Example. open and read an existing file

f = open("myFile.txt", 'r')
content = # 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 = # 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

Example: of sequential read

f = open("myFile.txt", 'r')
s = ""
for c in
    s = s + c
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 =
    if c == "":
    s = s + c

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 == ""):
    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


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:
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

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') # selection of position 5
print( #read the file from the 6 th position

Younes Derfoufi

No comments:

Post a Comment

Python Exercises With Solutions

  1. Exercises on Python Strings
  2. Exercises on Python lists
  3. OOP Exercices with solutions
  4. Exercises on Python File I/O
  5. Python Dictionary Exercises
  6. Python Sets Exercises
  1. Python Arithmetic Exercises
  2. Equations & System Of Equations
  3. Polynomials and Functions
  4. Python Arithmetic Exercises 
  5. Numpy, Matplolib, Sympy , Scipy - Exercises
  6. Python Arithmetic Exercises
  1. Python GUI Tkinter Exercises

Younes Derfoufi

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (2) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (256) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) Bootstrap CSS (1) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (14) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) HTML (7) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (36) Python BeautifulSoup (1) Python For Data Science (2) Python PyQt (12) Python Reference (1) Python Source Code (3) Python-Books (6) Python-DVD-Training (1) Python-Exercises (297) Python-Framework (1) Python-IDE (1) Python-Kivy-Framework (2) Python-Modules (1) Python-pdf (2) Python-pyQt (1) python-temp (3) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (4) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)

Sample text

Sample Text

Blogger Templates