file handle
Working of open() Function in Python
Before performing any operation on the file like reading or writing, first, we have to open that file. For this, we should use Python’s inbuilt function open() but at the time of opening, we have to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
- r: open an existing file for a read operation.
- w: open an existing file for a write operation. If the file already contains some data then it will be overridden but if the file is not present then it creates the file as well.
- a: open an existing file for append operation. It won’t override existing data.
- r+: To read and write data into the file. The previous data in the file will be overridden.
- w+: To write and read data. It will override existing data.
- a+: To append and read data from the file. It won’t override existing data.
Working in Read mode
There is more than one way to read a file in Python. Let us see how we can read the content of a file in read mode.
Example 1: The open command will open the file in the read mode and the for loop will print each line present in the file.
- Python3
Output:
Hello world
GeeksforGeeks
123 456
Example 2: In this example, we will extract a string that contains all characters in the file then we can use file.read().
- Python3
Output:
Hello world
GeeksforGeeks
123 456
Example 3: In this example, we will see how we can read a file using the with statement.
- Python3
Output:
Hello world
GeeksforGeeks
123 456
Example 4: Another way to read a file is to call a certain number of characters like in the following code the interpreter will read the first five characters of stored data and return it as a string:
- Python3
Output:
Hello
Example 5:
We can also split lines while reading files in Python. The split() function splits the variable when space is encountered. You can also split using any characters as you wish.
- Python3
Output:
['Hello', 'world']
['GeeksforGeeks']
['123', '456']
Creating a File using the write() Function
Just like reading a file in Python, there are a number of ways to write in a file in Python. Let us see how we can write the content of a file using the write() function in Python.
Working in Write Mode
Let’s see how to create a file and how the write mode works.
Example 1: In this example, we will see how the write mode and the write() function is used to write in a file. The close() command terminates all the resources in use and frees the system of this particular program.
- Python3
Output:
This is the write commandIt allows us to write in a particular file
Example 2: We can also use the written statement along with the with() function.
- Python3
Output:
Hello World!!!
Working of Append Mode
Let us see how the append mode works.
Example: For this example, we will use the file created in the previous example.
- Python3
Output:
This is the write commandIt allows us to write in a particular fileThis will add this line
There are also various other commands in file handling that are used to handle various tasks:
rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are working with code. That explains why it’s good practice to use them with a statement where applicable. This is helpful because using this method any files opened will be closed automatically after one is done, so auto-cleanup.
Implementing all the functions in File Handling
In this example, we will cover all the concepts that we have seen above. Other than those, we will also see how we can delete a file using the remove() function from Python os module.
- Python3
Open a File
Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s).
- Text files: In this type of file, each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in Python by default. In the case of CSV(Comma Separated Files, the EOF is a comma by default.
- Binary files: In this type of file, there is no terminator for a line, and the data is stored after converting it into machine-understandable binary language, i.e., 0 and 1 format.
Refer to the below articles to get an idea about the basics of file handling.
Opening a File in Python
Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode). Now, the question arises what is the access mode? Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. The file handle is like a cursor, which defines where the data has to be read or written in the file. There are 6 access modes in Python.
Mode | Description |
---|---|
‘r’ | Open text file for reading. Raises an I/O error if the file does not exist. |
‘r+’ | Open the file for reading and writing. Raises an I/O error if the file does not exist. |
‘w’ | Open the file for writing. Truncates the file if it already exists. Creates a new file if it does not exist. |
‘w+’ | Open the file for reading and writing. Truncates the file if it already exists. Creates a new file if it does not exist. |
‘a’ | Open the file for writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist. |
‘a+’ | Open the file for reading and writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist. |
‘rb’ | Open the file for reading in binary format. Raises an I/O error if the file does not exist. |
‘rb+’ | Open the file for reading and writing in binary format. Raises an I/O error if the file does not exist. |
‘wb’ | Open the file for writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist. |
‘wb+’ | Open the file for reading and writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist. |
‘ab’ | Open the file for appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist. |
‘ab+’ | Open the file for reading and appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist. |
Syntax:
File_object = open(r"File_Name", "Access_Mode")
Note: The file should exist in the same directory as the Python script, otherwise full address of the file should be written. If the file is not exist, then an error is generated, that the file does not exist.
Opening a file in read mode in Python
In this example, we are reading data from a Txt file. We have used read() to read the data.
- Python3
Output:
Welcome to GeeksForGeeks!!
Note: In the above example, we haven’t provided the access mode. By default, the open() function will open the file in read mode, if no parameter is provided.
Adding data to the existing file in Python
If you want to add more data to an already created file, then the access mode should be ‘a’ which is append mode, if we select ‘w’ mode then the existing text will be overwritten by the new data.
- Python3
Output:
Opening a file with write mode in Python
In this example, we are using ‘w+’ which deleted the content from the file, writes some data, and moves the file pointer to the beginning.
- Python3
Output :
Reading Data from File Using Line By Line Using readline()
The readline() method in Python is used to read a single line from a file that has been opened for reading. When readline() is used in the code, it reads the next line of the file and returns it as a string.
In this example, we are reading data line by line from a file named test.txt and printing it into the terminal.
- Python3
Output:
How to read from a file
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s).
- Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default.
- Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine-understandable binary language.
Note: To know more about file handling click here.
Access mode
Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Different access modes for reading a file are –
- Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
- Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.
- Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Note: To know more about access mode click here.
Opening a File
It is done using the open() function. No module is required to be imported for this function.
Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file should be written on place of filename. Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For example, if there is \temp in the file address, then \t is treated as the tab character and error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in same directory and address is not being placed.
- Python3
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode.
Syntax:
File_object.close()
- Python3
Reading from a file
There are three ways to read data from a text file.
- read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
File_object.read([n])
- readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
- readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes.
Example:
- Python3
Output:
Output of Read function is Hello This is Delhi This is Paris This is London Output of Readline function is Hello Output of Read(9) function is Hello Th Output of Readline(9) function is Hello Output of Readlines function is ['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
With statement
with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources.
Syntax:
with open filename as file:
- Python3
Output:
Hello This is Delhi This is Paris This is London
Writing
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s).
- Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default.
- Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine-understandable binary language.
Note: To know more about file handling click here.
Table of content
Access mode
Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Different access modes for reading a file are –
- Write Only (‘w’) : Open the file for writing. For an existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist.
- Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
- Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Note: To know more about access mode click here.
Opening a File
It is done using the open() function. No module is required to be imported for this function. Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file should be written on place of filename. Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For example, if there is \temp in the file address, then \t is treated as the tab character and error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in same directory and address is not being placed.
- Python3
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode. Syntax:
File_object.close()
- Python3
Writing to file
There are two ways to write in a file.
- write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
- writelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Note: ‘\n’ is treated as a special character of two bytes. Example:
- Python3
Output:
Hello This is Delhi This is Paris This is London
Appending to a file
When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. Let’s see the below example to clarify the difference between write mode and append mode.
- Python3
Output:
Output of Readlines after appending This is Delhi This is Paris This is London Today Output of Readlines after writing Tomorrow
With statement
with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources. Syntax:
with open filename as file:
- Python3
Output:
Hello This is Delhi This is Paris This is London
Note: To know more about with statement click here.
using for statement:
steps:
To write to a file in Python using a for statement, you can follow these steps:
Open the file using the open() function with the appropriate mode (‘w’ for writing).
Use the for statement to loop over the data you want to write to the file.
Use the file object’s write() method to write the data to the file.
Close the file using the file object’s close() method.
In this example, the file is opened for writing using the with open(‘file.txt’, ‘w’) as f statement. The data to be written is stored in a list called data. The for statement is used to loop over each line of data in the list. The f.write(line + ‘\n’) statement writes each line of data to the file with a newline character (\n) at the end. Finally, the file is automatically closed when the with block ends.
- Python3
This is the first line This is the second line This is the third line
Approach:
The code opens a file called file.txt in write mode using a with block to ensure the file is properly closed when the block ends. It defines a list of strings called data that represents the lines to be written to the file. The code then uses a for loop to iterate through each string in data, and writes each string to the file using the write() method. The code appends a newline character to each string to ensure that each string is written on a new line in the file. The code optionally prints each string as it is written to the file.
Time Complexity:
Both the original code and the alternative code have a time complexity of O(n), where n is the number of lines to be written to the file. This is because both codes need to iterate through each line in the data list to write it to the file.
Space Complexity:
The original code and the alternative code have the same space complexity of O(n), where n is the number of lines to be written to the file. This is because both codes need to create a list of strings that represent the lines to be written to the file.
Comments
Post a Comment