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:

  1. r: open an existing file for a read operation.
  2. 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.
  3. a:  open an existing file for append operation. It won’t override existing data.
  4.  r+:  To read and write data into the file. The previous data in the file will be overridden.
  5. w+: To write and read data. It will override existing data.
  6. 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.

# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')
 
# This will print every line one by one in the file
for each in file:
    print (each)

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()

# Python code to illustrate read() mode
file = open("geeks.txt", "r")
print (file.read())

Output:

Hello world
GeeksforGeeks
123 456

Example 3: In this example, we will see how we can read a file using the with statement.

# Python code to illustrate with()
with open("geeks.txt") as file
    data = file.read()
 
print(data)

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: 

# Python code to illustrate read() mode character wise
file = open("geeks.txt", "r")
print (file.read(5))

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.

# Python code to illustrate split() function
with open("geeks.txt", "r") as file:
    data = file.readlines()
    for line in data:
        word = line.split()
        print (word)

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. 

# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

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.

# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f:
    f.write("Hello World!!!")

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.

# Python code to illustrate append() mode
file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()

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.

import os
 
def create_file(filename):
    try:
        with open(filename, 'w') as f:
            f.write('Hello, world!\n')
        print("File " + filename + " created successfully.")
    except IOError:
        print("Error: could not create file " + filename)
 
def read_file(filename):
    try:
        with open(filename, 'r') as f:
            contents = f.read()
            print(contents)
    except IOError:
        print("Error: could not read file " + filename)
 
def append_file(filename, text):
    try:
        with open(filename, 'a') as f:
            f.write(text)
        print("Text appended to file " + filename + " successfully.")
    except IOError:
        print("Error: could not append to file " + filename)
 
def rename_file(filename, new_filename):
    try:
        os.rename(filename, new_filename)
        print("File " + filename + " renamed to " + new_filename + " successfully.")
    except IOError:
        print("Error: could not rename file " + filename)
 
def delete_file(filename):
    try:
        os.remove(filename)
        print("File " + filename + " deleted successfully.")
    except IOError:
        print("Error: could not delete file " + filename)
 
 
if __name__ == '__main__':
    filename = "example.txt"
    new_filename = "new_example.txt"
 
    create_file(filename)
    read_file(filename)
    append_file(filename, "This is some additional text.\n")
    read_file(filename)
    rename_file(filename, new_filename)
    read_file(new_filename)
    delete_file(new_filename)

utput:

File example.txt created successfully.
Hello, world!

Text appended to file example.txt successfully.
Hello, world!
This is some additional text.

File example.txt renamed to new_example.txt successfully.
Hello, world!
This is some additional text.

File new_example.txt deleted successfully.

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.

open-file-python

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.

# Python program to demonstrate
# opening a file
 
 
# Open function to open the file "myfile.txt"
# (same directory) in read mode and store
# it's reference in the variable file1
 
file1 = open("myfile.txt")
 
# Reading from file
print(file1.read())
 
file1.close()

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.

# Python program to demonstrate
# opening a file
 
 
# Open function to open the file "myfile.txt"
# (same directory) in append mode and store
# it's reference in the variable file1
file1 = open("myfile.txt" , "a" )
 
# Writing to file
file1.write("\nWriting to file:)" )
 
# Closing file
file1.close()

Output:

Open a File in Python

 

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.

# Open a file for writing and reading
file = open('test.txt', 'w+')
 
# Write some data to the file
file.write('Hello, world!')
 
# Move the file pointer back to the beginning of the file
file.seek(0)
 
# Read the data from the file
data = file.read()
 
# Print the data to the console
print(data)
 
# Close the file when you're done
file.close()

Output :

Open a File in Python

Hello World 

Python Hello World

Terminal 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.

# Open a file for reading
file = open('test.txt', 'r')
 
# Read the first line of the file
line = file.readline()
 
# Loop through the rest of the file and print each line
while line:
    print(line)
    line = file.readline()
 
# Close the file when you're done
file.close()
Readline file

Test file

Output:

Readline Python 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 –

  1. 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.
  2. 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.
  3. 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. 

# Open function to open the file "MyFile1.txt" 
# (same directory) in read mode and
file1 = open("MyFile.txt", "r")
   
# store its reference in the variable file1 
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt", "r+")

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()

# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt", "r")
file1.close()

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: 

# Program to show various ways to
# read data from a file.
 
# Creating a file
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
 
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
file1.close()  # to change file access modes
 
file1 = open("myfile.txt", "r+")
 
print("Output of Read function is ")
print(file1.read())
print()
 
# seek(n) takes the file handle to the nth
# byte from the beginning.
file1.seek(0)
 
print("Output of Readline function is ")
print(file1.readline())
print()
 
file1.seek(0)
 
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
 
file1.seek(0)
 
print("Output of Readline(9) function is ")
print(file1.readline(9))
print()
 
file1.seek(0)
 
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()

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:

# Program to show various ways to
# read data from a file.
 
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
 
# Creating a file
with open("myfile.txt", "w") as file1:
    # Writing data to a file
    file1.write("Hello \n")
    file1.writelines(L)
    file1.close()  # to change file access modes
 
with open("myfile.txt", "r+") as file1:
    # Reading from a file
    print(file1.read())

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 –

  1. 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.
  2. 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.
  3. 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. 

# Open function to open the file "MyFile1.txt" 
# (same directory) in read mode and
file1 = open("MyFile.txt", "w")
   
# store its reference in the variable file1 
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt", "w+")

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()

# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt", "w")
file1.close()

Writing to file

There are two ways to write in a file.

  1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
  1. 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: 

# Python program to demonstrate
# writing to file
 
# Opening a file
file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"
 
# Writing a string to file
file1.write(s)
 
# Writing multiple strings
# at a time
file1.writelines(L)
 
# Closing file
file1.close()
 
# Checking if the data is
# written to file or not
file1 = open('myfile.txt', 'r')
print(file1.read())
file1.close()

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. 

# Python program to illustrate
# Append vs write mode
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.writelines(L)
file1.close()
 
# Append-adds at last
file1 = open("myfile.txt", "a")  # append mode
file1.write("Today \n")
file1.close()
 
file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()
 
# Write-Overwrites
file1 = open("myfile.txt", "w")  # write mode
file1.write("Tomorrow \n")
file1.close()
 
file1 = open("myfile.txt", "r")
print("Output of Readlines after writing")
print(file1.read())
print()
file1.close()

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:

# Program to show various ways to
# write data to a file using with statement
 
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
 
# Writing to file
with open("myfile.txt", "w") as file1:
    # Writing data to a file
    file1.write("Hello \n")
    file1.writelines(L)
 
# Reading from file
with open("myfile.txt", "r+") as file1:
    # Reading form a file
    print(file1.read())

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.

# Open the file for writing
with open('file.txt', 'w') as f:
    # Define the data to be written
    data = ['This is the first line', 'This is the second line', 'This is the third line']
    # Use a for loop to write each line of data to the file
    for line in data:
        f.write(line + '\n')
        # Optionally, print the data as it is written to the file
        print(line)
# The file is automatically closed when the 'with' block ends
Output
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

Popular posts from this blog

basic code