-
A file is some information or data which stays in the computer storage devices.
-
Generally, we divide files into two categories, text file, and binary file. Text files are the simple text whereas the binary files contain binary data which is only readable by a computer
-
Python has several functions for creating, reading, updating, and deleting files.
There are mainly different 3 operations can be performed on the file.
- Open file
- Read or write file
- close file.
-
for opening a file in Python one named open() methods are available.
-
The open function takes two arguments
- filename
- mode of file
Syntax:
File_to_open=open(filename,mode)
Where Filename; required Mode:is optional bydefault mode is read
- Read mode
- This mode opens a file for reading purposes.
- If the file does not exist this will generate an error.
Syntax:
fileobj=open(filename,"r")
Example:
fileobj=open("myfile.txt","r")
Above example give an error if file is not exists.
- Append mode
- This mode is used when we want to append content to the end of the file without overwintering the previous content.
- If the file does not exist a mode creates a new file.
Syntax:
fileobj=open(filename,"a")
Example:
fileobj=open("myfile.txt","a")
- Write mode
- This mode is used when we want to overwrite some content to file.
- If the file does not exist it will create a new file.
Syntax:
fileobj=open(filename,"w")
Example:
fileobj=open("myfile.txt","w")
- Exclusive Create.
- This mode is used to create a specified file.
- If the file already exists then it will give an error
Syntax:
fileobj=open(filename,"x")
Example:
fileobj=open("myfile.txt","x")
the file should be handled as binary or text mode using the following 2 modes
- b binary file
- t text file
Example 1:
Consider mylog.txt file in your current directory and you want to open it
#defualt read mode
fil=open("mylog.txt")
#Using r mode
fil=open("mylog.txt","r")
#using read and text mode
fil=open("mylog.txt","rt")
Above all example open a text file for reading the purpose
Example 2:
Open file for writing purpose
fil=open("mylog.txt","w")
When you want to read and write on the same file you can pass both modes to open() function
Syntax:
fileobj=open(filename,"mode1mode2")
Example:
fileobj=open("myfile.txt","rwt")
Here file is opened in three different mode for reading,writing a text file
Note:after completion of file operation don't forgot to close file using filename.close()
- With the with statement, you get better syntax and exceptions handling.
- Using with keyword the file is automatically closed when the operation is completed.we don't need to write
fileobj.close()
Syntax:
with open(filename,mode) as fileobj:
#do operation on fileobj
Example:
Consider mytext.txt contains
Hello I am from file
with open("mytext.txt","r") as file:
content=file.read()
print(content)
Output:
Hello I am from file