Min menu

Pages

files in Python

Working with files in Python

Dealing with files or processing files(Files Handling)It is intended to perform an operation on files of all kinds( Such astxt-jpg-mp4).
In this lesson, you will learn how to read the content of a file, how to create a copy of it, how to modify its content, how to delete it, etc.

function open()in python

This function is one of the ready-made functions in Python and is used to create a new file or to open the file that will be handled.
If the file was created correctly or the file opened correctly, it returns an object that fileallows you to work with it.
If you cannot create or access the file, an exception is thrown.


built

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None)
	  

  • In place of the parameter, filewe pass a text representing the name of the file to be created or handled.

  • modeIt is an optional parameter, we pass in its place a letter( Or more )It represents how we will deal with the file, such as: do you intend to read from it or write to it, etc..

  • bufferingIt is an optional parameter, you can pass in its place a number that specifies how characters will be cached in memory while writing or reading from a file.

  • encodingIt is an optional parameter, in its place you can pass the name of the encoding that should be used when working with the file.

  • errorsIt is an optional parameter, you can pass in its place a word to specify how errors that may occur when working with the file will be handled.

  • newlineIt is an optional parameter, you can pass in its place the symbol that represents the end of each line in the file and that makes the text that is placed some of it down on a new line.



The most important optional parameter in this function is the parameter modebecause, as we have already said, the character we pass in its place determines the purpose of opening the file.
In the following table we put all the characters that can be passed in place of this parameter.

character its meaning Example
'r' It is an abbreviation of the wordRead,It is used to open the file in order to read from it.
It is alsotheModeThe default for the file you open.
see example »
'w' It is an abbreviation of the wordWrite,And it is used to open the file in order to write in it.
And if the file to be written in does not already exist, it will be created.
Note: This character deletes the text that was present in the file if it is not empty.
see example »
'a' It is an abbreviation of the wordAppend,And it is used to open the file in order to write at the end. That is, to add new text to the existing text in the file.
And if the file to be written in does not already exist, it will be created.
see example »
'x' It is an abbreviation of the wordCreate,It is used to create a new file only if it does not exist. see example »
't' It is an abbreviation of the wordText,It is used to specify that the file content is plain text.
It is alsotheModeThe default for the file you open.
see example »
'b' It is an abbreviation of the wordBinary,It is used to specify that the file content isBinary, Which characters can not be understood by the average person.
thistheModeWe use it when dealing with non-text files such as images, videos, audio recordings, etc..
Note: The example will teach you how to create a copy of any file.
see example »
'+' It is an abbreviation of the two wordsRead & Write,It is used to open the file with the ability to read from it and write to it at the same time. see example »

A note about files in Python

The characters mentioned in the table can be combined with each other, that is, you can select more than oneModeat same time.
For example, you can type 'wb'in order to open a new file and put the text of its typeBinaryLike we do if we want to copy an image for example.


In the following example, we have created a new text file named demo.txtin the same project we are working on.
Then we wrote the following line inside itPython is an easy language to learn..

Example

Test.py
# In order to create the file and to be able to write in it also 'w' and we put the symbol 'demo.txt' here we created an object pointing to a file named
		  opened_file = open('demo.txt', 'w')
	  
		  # To write to the file that opened_file points to from the write() object here we called the function
		  opened_file.write('Python is an easy language to learn.')
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, a file with its name will be created demo.txtin the same project we are working in, with the following text inside it.

Python is an easy language to learn.

Read and write functions in files in Python

After successfully opening the file that you want to handle with the function open(), you can use the following functions from the object returned by this function.

Function name and definition
write(string) Used to write to the object representing the open file that called it.
Parameter location stringWe pass the text that we want to be written to the file.
see example »
writelines(aList) Used to write a set of texts stored in listthe object representing the open file that called it.
Where the parameter is lineswe pass an object aListwith the set of texts that we want to be written in the same order in the file.
see example »
read(n = -1) Used to read from the object representing the open file that called it.
If you call it and do not pass a number to it, it will return all the text in the file at once.
nIt is an optional parameter. In its place, you can pass a number representing the number of characters you want to read from the file in case you do not want to read all the content of the file at once. Noting that every time you invoke it it will give you the following characters in the file.
see example »
readline(limits = -1) Uses to read line by line from the object representing the open file that called it.
If you invoke it and do not pass a number to it, it will return the next line in the file.
nIt is an optional parameter. In its place you can pass a number representing the number of characters you want to read from the next line in the file in case you do not want to read all the content of the line at once. Noting that every time you invoke it it will give you the characters that are up to the end of the current line in the file.
see example »
readlines(limits = -1) Used to return a copy of the text in the object representing the open file that called it as an objectlist.
Every element in an objectthelistThe one you are returning represents a line in the file.
If you call it and don't pass it any number, all the characters on each line in the file will be placed in an element of the objectThe list.
nIt is an optional parameter. In its place you can pass a number representing the number of characters you want to read from each line in the file in case you do not want to read all the content of the line.
see example »
tell() Returns the number of the last character in the file accessed while reading from the file by the object that represents that file.
see example »
seek(offset, from_what=0) While reading from the file by the object that represents this file, you can use this function if you want to go back in the file to read the file again for example.
from_whatIt is an optional parameter. You can pass one of the following numbers in its place:
  • The number 0 if you want to go back to the first character in the file.

  • Number 1 if you want to stay at the current character you arrived at in the file.

  • Number 2 if you want to go to the last character in the file.

Parameter position You offsetpass a number representing how many characters in relation to the parameter from_whatyou want to start.
Example: If you call the function like this seek(0,0)or like seek(0)this it means that you want to go back to the first character in the file.
see example »
close() It is used to close the connection with the file and to clean the memory of everything related to this file.
Note: If you originally opened the file by sentence , there is withno need to close the file because it automatically closes it for you.
see example »

File properties in Python

In addition to the above functions, you can take advantage of the following properties of the object returned by the functionopen().

The name of the property and its definition
name Returns the name of the file that the object represents.
mode Returns the character or characters used to specify the intent of opening the file.
encoding Returns the name of the encoding used in the file that the object represents.
closed Used to find out if the object representing the file is still open or closed.
Return Trueif so, if not, returnFalse.


In the following example, we have created an object pointing to the file demo.txtwe created earlier.
Then we display the properties of this object, which in turn are the properties of the file itself.

Example

Test.py
# 'demo.txt' Here we have created an object pointing to a file named
		  opened_file = open('demo.txt')
	  
		  # which refers to the file opened in memory opened_file here we have shown all the properties of the object
		  print('File Name:', opened_file.name)
		  print('Access Mode:', opened_file.mode)
		  print('Encoding Type:', opened_file.encoding)
		  print('Is File closed:', opened_file.closed)
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

We will get the following result when we run the fileTest.py.

File Name: demo.txt
Access Mode: w
Encoding Type: cp1252
Is File closed: False

 Module osin Python

osIt is a ready-made module in Python that allows you to rename files, delete files, create folders, delete folders, move between folders etc..

To use this module it must be included as follows.

import os
	  


The following table contains the functions of the osmost commonly used modules.

Function name and definition
os.rename(current_file_name, new_file_name) Used to change the file name.
In place of the parameter current_file_name, we pass the name of the file whose name we want to change.
In place of the parameter new_file_namewe pass the new name that we want to put for the file.
see example »
os.remove(file_name) Used to scan the file.
The location of the parameter file_namewe pass the name of the file we want to delete.
see example »
os.path.exists(file_name) Used to check if the file exists or not.
The location of the parameter file_namewe pass the name of the file we want to check whether it exists or not.
Returns Trueif the file exists. And return Falseif not.
see example »
os.mkdir(directory_name) Used to create a new folder.
Parameter location directory_nameWe pass the name of the folder we want to create.
Information: The function name is an abbreviation of a sentenceMake Directory.
see example »
os.rmdir(directory_name) Used to scan the folder.
The location of the parameter directory_namewe pass the name of the folder we want to delete.
Note: You can delete the folder only if it is empty, that is, if it does not contain any file inside.
Information: The function name is an abbreviation of a sentenceRemove Directory.
see example »
os.getcwd() It is used to find the name of the folder you are currently in.
Information: The function name is an abbreviation of a sentenceGet Current Working Directory.
see example »

 Block within Python

You can benefit from using the block method withif you want the files that you open in your programs to be closed automatically and without the need to call the functionclose().


How to define a block?with:

with expression [as variable]:
		#with-block
  

  • expression:In its place we put the command, which will return us an object pointing to the file that was opened in memory.

  • variable:In its place we put the name of the object with which we want to deal with the file that was opened in memory.

  • #with-block:In the place of this comment we put the commands that we want to execute after the file has been successfully opened.



In the following example, we opened a file and read the text in it without having to close it when it was finished because we put the code inside the word blockwith.

Example

Test.py
# Then we print the text in it 'demo.txt' refers to the file opened_file here we created an object named
		  with open('demo.txt', 'r') as opened_file:
		  print(opened_file.read())
	  
		  # Here we print whether the file is still open in memory or if it is closed
		  print('Is File Closed:', opened_file.closed)
	

After running the file , all the text in the file that we assumed we created earlier in the same project we are working on Test.pywill be printed . We note that the function returned the value , and this means that the file was closed from memory automatically when the block expireddemo.txt
closed()Truewith.

Python is an easy language to learn.
Is File Closed: True

Storing Arabic characters in a file in Python

If you try to write Arabic characters in a file and do not specify that the type of encoding used when dealing with the file isutf-8The error will appear'charmap' codec can't encode .
And if you try to read an Arabic text in a file and do not specify the type of encoding, you will notice that the text appears in an incomprehensible way as followsالسلام عليكم.


In the following example, we created a file called arabic.txt, we stored an Arabic text in it, and then we read the text in it.

Example

Test.py
# 'Test.py' will be created in the same project next to the file 'arabic.txt' pointing to a new file named opened_file here we created an object named
		  # To be able to deal with the Arabic characters 'utf-8' until the file is created and we have the ability to write and read from it at the same time. Also we have set the encoding type is 'w+' and set the symbol
		  opened_file = open('arabic.txt', 'w+', encoding='utf-8')
	  
		  # To write a new text in the file it refers to and note that we entered the Arabic text opened_file from the write() object here we called the function
		  opened_file.write('Peace be upon you and God's mercy and blessings')
	  
		  # To return to the first file seek() here we called the function
		  opened_file.seek(0,0)
	  
		  # which refers to the open file until it returns all the text in it, then we print the text that you will return opened_file from the read() object here we called the function
		  print(opened_file.read())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file, the file Test.pywill be created arabic.txtand the Arabic text stored in it. Also, the original Arabic text inside the file will be printed as follows.

Peace, mercy and blessings of God

Safe handling of files in Python

When dealing with files, you may encounter several problems that may be caused by the operating system or the user.
Therefore, you should always protect the code through which you will deal with files with the sentences try.. exceptthat we explained earlier.


Some of the problems that may occur with you while dealing with files:

  • If the path of the file you want to work with is listed incorrectly.

  • If you are trying to read the content of a file that does not already exist or has been deleted.

  • If you want to write in Arabic and do not specify that the type of encoding that should be used is'utf-8'.

  • If you are trying to work with an image or video and do not specify that the type of this file isBinaryAs we explained a while ago.

  • If the file has read-only permission(Read Only)You cannot modify the text in it in any way or delete the file itself from the computer.

  • In the event that you want to create a folder or file and you do not have the permissions that authorize you to do so. For example, in Windows, you cannot create a file on the pathC:\If you do not have administrator privileges.


In the following example, we will open the file and deal with it inside a block try.. exceptto ensure that no problem occurs that leads to the suspension of the program and to display any error that may occur as well.

first example

Test.py
# In order to display the text containing 'harmash.txt' here we tried to find and open a file named
		  try:
		  opened_file = open('harmash.txt', 'r')
		  print(opened_file.read())
		  opened_file.close()
	  
		  # and then display it as plain text ex Since there is no such file in the project, the information of the error that occurred will be stored in the object
		  except Exception as ex:
		  print(ex)
	  
		  print('Program still working properly')
	

After running the file , the Test.pyproblem that occurred while trying to read from the file will be printed as plain text and this will not cause the program to hang.

[Errno 2] No such file or directory: 'harmash.txt'
Program still working properly


Here we have completely repeated the previous example, but we tried to open the file with the blockwith.
Note that the result is the same in both cases.

second example

Test.py
# In order to display the text containing 'harmash.txt' here we tried to find and open a file named
		  try:
		  with open('harmash.txt', 'r') as opened_file:
		  print(opened_file.read())
	  
		  # and then display it as plain text ex Since there is no such file in the project, the information of the error that occurred will be stored in the object
		  except Exception as ex:
		  print(ex)
	  
		  print('Program still working properly')
	

After running the file , the Test.pyproblem that occurred while trying to read from the file will be printed as plain text and this will not cause the program to hang.

[Errno 2] No such file or directory: 'harmash.txt'
Program still working properly

  Read text in a file in Python

Remember: the symbol rwe put in the function open()is an abbreviation for the wordRead,It is used to open the file in order to read from it.
It is alsotheModeThe default for the file you open.


Example

Test.py
                    # to indicate that we will use this object to read from file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the opened file to return the text in it, then we print the text that you will return opened_file from the read() object here we called the function
		  print(opened_file.read())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After playing the file , Test.pythe content of the file will be read demo.txtand then displayed as follows.

Python is an easy language to learn.     <-- Here we assumed that this text was already in the file

  Storing text in a file in Python

Remember: the symbol wwe put in the function open()is an abbreviation for the wordWrite,And it is used to open the file in order to write in it.
And if the file to be written in does not already exist, it will be created.
And do not forget that this character deletes the text that was present in the file if it is not empty.


Example

Test.py
                    # to indicate that we are going to use this object to write a new text in the file 'w' and put the symbol 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'w')
	  
		  # To write new text in the file that opened_file points to from the write() object here we called the function
		  opened_file.write('This new text will replace the old text.')
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, a file with its name will be created demo.txtin the same project we are working in, with the following text inside it.

This new text will replace the old text.

  Add new text to existing text in a file in Python

Remember: the symbol awe put in the function open()is an abbreviation for the wordAppend,And it is used to open the file in order to write at the end.
It is used to add new text to the existing text in the file.
And if the file to be written in does not already exist, it will be created.


Example

Test.py
                    # to indicate that we will use this object to add new text to the text in file 'a' and put the symbol 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'a')
	  
		  # To add new text in the file that opened_file points to from the write() object here we called the function
		  opened_file.write('\nThis new text')
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

If you run the file Test.pyand no problem occurs, you will find that the file demo.txthas the text added "This new text"on a new line.

Old text in the file.     <-- If we assume that this text was present in the file
This new text             <-- the following line will be added at the end of the file as follows

 How to create a new file in Python

Remember: the symbol xwe put in the function open()is an abbreviation for the wordCreate,It is used to create a new file only if it does not exist.


Example

Test.py
                    # To indicate that we want to create this file in case it does not already exist 'x' and we put the symbol 'demo.txt' here we have created a new file named
		  open('demo.txt', 'x')
	

After running the Test.pyfile, an empty file will be created with its name demo.txtin the same project we are working on.
If there is a file named demo.txtin the same project we are working in, the following error will appear.

FileExistsError: [Errno 17] File exists: 'demo.txt'

  Read text in a text file in Python

Remember: the symbol twe put in the function open()is an abbreviation for the wordText,It is used to specify that the file content is plain text.
It is alsotheModeThe default is for the file you open, so you don't need to mention it if you're working with a text file.


Example

Test.py
                    # to specify that the file type is a text file 't' to indicate that we are going to use this object to read from the file, and we put the 'r' and the 'demo.txt' here we created an object pointing to a file named
		  opened_file = open('demo.txt', 'rt')
	  
		  # which refers to the opened file to return the text in it, then we print the text that you will return opened_file from the read() object here we called the function
		  print(opened_file.read())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After playing the file , Test.pythe content of the file will be read demo.txtand then displayed as follows.

Python is an easy language to learn.     <-- Here we assumed that this text was already in the file

  Create a copy of an image or video in Python

Remember: the symbol bwe put in the function open()is an abbreviation for the wordBinary,It is used to specify that the file content isBinary, Which characters can not be understood by the average person.
thistheModeWe use it when dealing with non-text files such as images, videos, audio recordings, etc.


Note: In the following example, we assume that you put an image in the project whose name is logo.pngnext to the fileTest.py.
To add any image in the project manually, you can copy the image from your computer and then paste it into the project(Copy / Paste).

Example

Test.py
                    # which represents the image whose content we want to copy 'logo.png' here we have created an object pointing to a file named
		  # to specify that we are dealing with a non-text file 'b' to indicate that we are going to use this object to read from the file, and put the symbol 'r' put the symbol
		  existing_file = open('logo.png', 'rb')
	  
		  # which represents the new image that will be created and copy the content in it 'logo-2.png' Here we have created an object pointing to a new file named
		  # to specify that we are dealing with a non-text file 'b' to indicate that we will use this object to write to the file after it has been created, and put the symbol 'w' and put the symbol
		  new_file = open('logo-2.png', 'wb')
	  
		  # read() pointing to the first image by the existing_file function here we have read the content of the object
		  # which points to the second image new_file and then stores the text you return in the object
		  new_file.write(existing_file.read())
	  
		  # To close the connection with the two files open in memory new_file and existing_file from object close() here we called the function
		  existing_file.close()
		  new_file.close()
	

After running the file Test.py, an exact copy of the image with its logo.pngname will be made logo-2.pngin the same project.

  Create an object that allows reading and writing from a file simultaneously in Python

Remember: the symbol awe put in the function open()is an abbreviation of the two wordsRead & Write,It is used to open the file with the ability to read from it and write to it at the same time.


Example

Test.py
                    # to indicate that we will use this object to add new text to the text in file 'a' and put the symbol 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'a+')
	  
		  # To add new text in the file that opened_file points to from the write() object here we called the function
		  opened_file.write('\nhis new text')
	  
		  # To get back to the first character in the file that the opened_file of the seek() object points to here we called the function
		  opened_file.seek(0, 0)
	  
		  # which refers to the opened file to return the text in it, then we print the text that you will return opened_file from the read() object here we called the function
		  print(opened_file.read())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

If you run the file Test.pyand no problem occurs, you will find that the file demo.txthas the text added "This new text"on a new line.
Also we will get the following result when running.

Old text in the file.     <-- Suppose this line was in the file
This new text

 Functionwrite() في بايثون

its definition

Used to write to the object representing the open file that called it.



built

                  write(string)
	  


parameters

Parameter location stringWe pass the text that we want to be written to the file.


Return value

It does not return a value.


Example

Test.py
                    # to indicate that we are going to use this object to write a new text in the file 'w' and put the symbol 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'w')
	  
		  # To write new text in the file that opened_file points to from the write() object here we called the function
		  opened_file.write('This new text will replace the old text.')
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, a file with its name will be created demo.txtin the same project we are working in, with the following text inside it.

This new text will replace the old text.

Python  functionwritelines()

its definition

Used to write a set of texts stored in listthe object representing the open file that called it.



built

                  writelines(aList)
	  


parameters

Where the parameter is aListwe pass an object listwith the set of texts that we want to be written in the same order in the file.


Return value

It does not return a value.


Example

Test.py
                    aList = ['text 1\n', 'text 2\n', 'text 3\n']
	  
		  # to indicate that we are going to use this object to write a new text in the file 'w' and put the symbol 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'w')
	  
		  # In the file that aList points to to write the element values ​​of the opened_file object from the writelines() object here we called the function
		  opened_file.writelines(aList)
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, a file with its name will be created demo.txtin the same project we are working in, with the following text inside it.

text 1
text 2
text 3

Python  functionread()

its definition

Used to read from the object representing the open file that called it.
If you call it and do not pass a number to it, it will return all the text in the file at once.



built

                  read(n = -1)
	  


parameters

nIt is an optional parameter. In its place, you can pass a number representing the number of characters you want to read from the file in case you do not want to read all the content of the file at once. Noting that every time you invoke it it will give you the following characters in the file.


Return value

Returns the text in the file.


In the following example, we used the function read()to read all the text in the file at once.

first example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the open file until it returns all the text in it, then we print the text that you will return opened_file from the read() object here we called the function
		  print(opened_file.read())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file , all the text in the file that we assumed we created in the same project we are working on Test.pywill be printed .demo.txt

Python is an easy language to learn.     <-- Here we assumed that this text was already in the file


In the following example, we used the function read()to read five characters from the file each time we called it.

second example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the open file and every time we make it return 5 new characters. Then we print these opened_file characters four times from the read() object here we call the function
		  print(opened_file.read(5))
		  print(opened_file.read(5))
		  print(opened_file.read(5))
		  print(opened_file.read(5))
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, every time the function is called, it read()will return the next five characters in the file demo.txtthat we assumed we created in the same project we are working on.

Pytho
n is
an ea
sy la

Python  functionreadline()

its definition

Uses to read line by line from the object representing the open file that called it.
If you invoke it and do not pass a number to it, it will return the next line in the file.



built

                  readline(limits = -1)
	  


parameters

limitsIt is an optional parameter. In its place you can pass a number representing the number of characters you want to read from the next line in the file in case you do not want to read all the content of the line at once. Noting that every time you invoke it it will give you the characters that are up to the end of the current line in the file.


Return value

Returns the next line in the file.


In the following example, we used the function readline()to read all the text in the file at once.

first example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which indicates the open file to return a new line from it each time. Then we print the line returned by opened_file three times from the readline() object, here we call the function
		  print(opened_file.readline())
		  print(opened_file.readline())
		  print(opened_file.readline())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file , the Test.pyfirst three lines in the file demo.txtthat we assumed we created in the same project we are working on will be printed.

First line

Second line

Third line


In the following example, we use the function .readline() to read six characters on the same line in the file each time we called it.

second example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the open file and every time we make it return 6 new characters from the current line. Then we print these opened_file characters three times from the readline() object here we call the function
		  print(opened_file.readline(6))
		  print(opened_file.readline(6))
		  print(opened_file.readline(6))
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, every time the function is called, it readline()will return the next six characters that are on the same lines in the file demo.txtthat we suppose we created in the same project we are working on.

First
line 

Second

Python  functionreadlines()

its definition

Used to return a copy of the text in the object representing the open file that called it as an objectlist.
Every element in an objectthelistThe one you are returning represents a line in the file.
If you call it and don't pass it any number, all the characters on each line in the file will be placed in an element of the objectThe list.



built

                  readlines(limits = -1)
	  


parameters

limitsIt is an optional parameter. In its place you can pass a number representing the number of characters you want to read from each line in the file in case you do not want to read all the content of the line.



Return value

Returns a copy of the text in as an objectlist,Each element in it is a line in the file.


In the following example, we used the function readlines()to read all the text in the file at once and return it as an objectlist.

first example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the opened file for you to return as an opened_file object from the readlines() object here we called the function
		  # Each statement element contains one of the lines in the file. Then we print it as a list
		  print(opened_file.readlines())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file , the Test.pyfirst three lines in the file demo.txtthat we assumed we created in the same project we are working on will be printed.

['First line\n', 'Second line\n', 'Third line']


In the following example we have created a loop forthat displays the content of the file line by line.

second example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the opened file for you to return as an opened_file object from the readlines() object here we called the function
		  # Each statement element contains one of the lines in the file. Then we print it as a list
		  # and then print its value line and store the element temporarily in the variable list then we pass through each element in the object
		  for line in opened_file.readlines():
		  print(line)
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, every line in the file demo.txtthat we assumed we created in the same project we are working on will be printed.

First line

Second line

Third line

Python  functiontell()

its definition

Returns the number of the last character in the file accessed while reading from the file by the object that represents that file.



built

                  tell()
	  


parameters

Do not accept any parameters.


Return value

Returns the number of the last character in the file accessed while reading from the file.


In the following example, we use the function tell()every time we read some characters from the file.

Example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the opened file until it returns the first 5 characters in the text, then we print the text that you will return opened_file from the read() object here we call the function
		  print('Characters read:', opened_file.read(5))
	  
		  # again read() here we print the number of the last character in the text that was printed, which will be printed after it when the function is called
		  print('Current file position:', opened_file.tell())
	  
		  # which refers to the opened file until it returns the second 5 characters in the text, then we print the text that you will return opened_file from the read() object here we call the function
		  print('Characters read:', opened_file.read(5))
	  
		  # again read() here we print the number of the last character in the text that was printed, which will be printed after it when the function is called
		  print('Current file position:', opened_file.tell())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, every time the function is called, it read()will return the next five characters in the file demo.txtthat we assumed we created in the same project we are working on.

Characters read: Self
Current file position: 5
Characters read: study
Current file position: 10

Python  functionseek()

its definition

While reading from the file by the object that represents this file, you can use this function if you want to go back in the file to read the file again for example.



built

                  seek(offset, from_what=0)
	  


parameters

  • from_whatIt is an optional parameter. You can pass one of the following numbers in its place:

    • The number 0 if you want to go back to the first character in the file.

    • Number 1 if you want to stay at the current character you arrived at in the file.

    • Number 2 if you want to go to the last character in the file.

  • Parameter position You offsetpass a number representing how many characters in relation to the parameter from_whatyou want to start.



Return value

It does not return a value.


In the following example, we use the function seek()to return to the beginning of the file after we have read the few characters from it.

Example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the open file until it returns the first 10 characters in the text, then we print the text that you will return opened_file from the read() object here we call the function
		  print('Characters read:', opened_file.read(10))
	  
		  # again read() here we print the character number after which it will be printed when the function is called
		  print('Current file position:', opened_file.tell())
	  
		  # and pass its values ​​0 and 0 to get back to the first character in the opened_file of the seek() object here we called the function
		  opened_file.seek(0, 0)
	  
		  # again read() here we print the character number after which it will be printed when the function is called
		  print('Current file position:', opened_file.tell())
	  
		  # which refers to the opened file until it returns the same 10 characters as before, then we print the text that you will return opened_file from the read() object here we call the function
		  print('Characters read again:', opened_file.read(10))
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file Test.py, every time the function is called, it read()will return the next five characters in the file demo.txtthat we assumed we created in the same project we are working on.

Characters read: Self study
Current file position: 10
Current file position: 0           <-- seek() The position 0 in the file means that we are back to the first file and this of course happened because of calling the function
Characters read again: Self study

Python  functionclose()

its definition

It is used to close the connection with the file and to clean the memory of everything related to this file.
Note: If you originally opened the file by sentence , there is withno need to close the file because it automatically closes it for you.



built

                  close()
	  


parameters

Do not accept any parameters.


Return value

It does not return a value.


In the following example, we used the function close()to close the open file in memory after we finished reading from it.

Example

Test.py
                    # to indicate that we are going to use this object to read the text in file 'r' and put the code 'demo.txt' here we have created an object pointing to a file named
		  opened_file = open('demo.txt', 'r')
	  
		  # which refers to the open file until it returns all the text in it, then we print the text that you will return opened_file from the read() object here we called the function
		  print(opened_file.read())
	  
		  # To close the connection with the file opened in memory opened_file from the object close() here we called the function
		  opened_file.close()
	

After running the file , all the text in the file that we assumed we created in the same project we are working on Test.pywill be printed .demo.txt

Python is an easy language to learn.     <-- Here we assumed that this text was already in the file

Python  functionrename()

its definition

Used to change the file name.



built

                  os.rename(current_file_name, new_file_name)
	  


parameters

  • In place of the parameter current_file_name, we pass the name of the file whose name we want to change.

  • In place of the parameter new_file_namewe pass the new name that we want to put for the file.



Return value

It does not return a value.


Example

Test.py
                    # So that we can use the functions in os here we have included the module
		  import os
	  
		  # 'my-demo.txt' to 'demo.txt' to change the file name rename() here we called the function
		  os.rename('demo.txt', 'my-demo.txt')
	

After running the file , Test.pythe name of the file demo.txtthat we assumed we created in the same project we are working in will be changed tomy-demo.txt.

Python  functionremove()

its definition

Used to scan the file.



built

                  os.remove(file_name)
	  


parameters

The location of the parameter file_namewe pass the name of the file we want to delete.



Return value

It does not return a value.


Example

Test.py
                    # So that we can use the functions in os here we have included the module
		  import os
	  
		  # 'demo.txt' to clear the file remove() here we called the function
		  os.remove('demo.txt')
	

After running the file , Test.pythe file demo.txtthat we assumed we created earlier in the same project will be deleted.

Python  functionpath.exists()

its definition

Used to check if the file exists or not.



built

                  os.path.exists(file_name)
	  


parameters

The location of the parameter file_namewe pass the name of the file we want to check whether it exists or not.



Return value

Returns Trueif the file exists. And return Falseif not.


Example

Test.py
                    # So that we can use the functions in os here we have included the module
		  import os
	  
		  # 'Test.py' is in the same place as the file 'demo.txt' To see if the file is path.exists() here we called the function
		  os.path.exists('demo.txt')
	

After running the file Test.py, the value will be printed Trueas follows if you have in the same project a file nameddemo.txt.
If a file name is not found, the demo.txtvalue will be printedFalse.

Python  functionmkdir()

its definition

Used to create a new folder.
Information: The function name is an abbreviation of a sentenceMake Directory.



built

                  os.mkdir(directory_name)
	  


parameters

Parameter location directory_nameWe pass the name of the folder we want to create.



Return value

It does not return a value.


Example

Test.py
                    # So that we can use the functions in os here we have included the module
		  import os
	  
		  # 'images' to create a folder named mkdir() here we called the function
		  os.mkdir('images')
	

After running the file Test.py, a folder with its name will be created imagesin the same project.

Python  functionrmdir()

its definition

Used to scan the folder.
Note: You can delete the folder only if it is empty, that is, if it does not contain any file inside.
Information: The function name is an abbreviation of a sentenceRemove Directory.



built

                  os.rmdir(directory_name)
	  


parameters

The location of the parameter directory_namewe pass the name of the folder we want to delete.



Return value

It does not return a value.


Example

Test.py
                    # So that we can use the functions in os here we have included the module
		  import os
	  
		  # 'images' to create a folder named rmdir() here we called the function
		  os.rmdir('images')
	

After running the file Test.py, a folder with its name will be imagesdeleted, assuming that it was present in the same project.

Python  functiongetcwd()

its definition

It is used to find the name of the folder you are currently in.
Information: The function name is an abbreviation of a sentenceGet Current Working Directory.



built

                  os.getcwd()
	  


parameters

Do not accept any parameters.



Return value

Returns the path you are currently in.


Example

Test.py
                    # So that we can use the functions in os here we have included the module
		  import os
	  
		  # Then we printed it. 'Test.py' to return the name of the folder in which the getcwd() file is located. Here we called the function
		  print(os.getcwd())
	

You will get a result similar to the following when running according to the path the file is in Test.pyon your computer.

C:\Users\Mhamad\PycharmProjects\myapp