File Handling in Python🤩
FILES IN PYTHON
Python has the feature to operate on files in python programming language. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important.
Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun.
The different features of file handling are discussed below:
Python has several functions for creating, reading, updating, and deleting files. The main command in the file handling is the open() command which is used to open/create the files according to the input given in it.
1. open(filename, mode) → open command consists of two parameters one is the name of the file and another one is called mode, there are several methods for opening a file they are,
r - Read - Default value. Opens a file for reading, error if the file does not exist
a - Append - Opens a file for appending, creates the file if it does not exist
w - Write - Opens a file for writing, creates the file if it does not exist
x - Create - Creates the specified file, returns an error if the file exists
In addition to this, we can use the following methods to read and write at the same time.
r+ → read and write → won’t override
w+ → Read and write → override the existing data
a+ → append and read → won’t override
In addition, you can specify if the file should be handled as binary or text mode
‘t’- Text - Default value. Text mode
‘b’ - Binary - Binary mode (e.g. images)
Example:
There is more than one way to read a file in Python. If you need to extract a string that contains all characters in the file then we can use file.read().
Example:
4. dir()
5. mode()
6. name()
7. close()
8. write()
9. tell()
10. seek()
11. readline()
12. readlines()
13. with
Creating a new file
As we discussed before we can create a new file by using write and append mode, while using it it will check whether the file is present or not. If the file is not present the code itself create a new file with the given name.
To create a new file in Python, use the
‘x’ - Create - will create a file, returns an error if the file exists
‘a’ - Append - will create a file if the specified file does not exist
‘w’ - Write - will create a file if the specified file does not exist
To create a new file in Python, use the
open()
method, with one of the following parameters:‘x’ - Create - will create a file, returns an error if the file exists
‘a’ - Append - will create a file if the specified file does not exist
‘w’ - Write - will create a file if the specified file does not exist
Comments
Post a Comment