Code icon

The App is Under a Quick Maintenance

We apologize for the inconvenience. Please come back later

Menu iconMenu iconPython Programming Unlocked for Beginners
Python Programming Unlocked for Beginners

Chapter 6: Working with Files

6.3: File Modes and Operations

When working with files in Python, it is essential to understand the different file modes and operations available. File modes determine how you can interact with a file (e.g., reading, writing, or appending), while file operations refer to the actions you perform on a file (e.g., reading content, writing content, or seeking a specific position). 

Here's a detailed explanation of common file modes:

  1. 'r': Read mode - In this mode, the file is opened for reading. You can only read the file's content, and the file must exist before opening. If the file doesn't exist, a FileNotFoundError will be raised.
  2. 'w': Write mode - In this mode, the file is opened for writing. If the file doesn't exist, it will be created. If it already exists, its content will be overwritten (i.e., truncated).
  3. 'a': Append mode - In this mode, the file is opened for appending. If the file doesn't exist, it will be created. If it already exists, new data will be added to the end of the file, preserving the original content. 
  4. 'x': Exclusive creation mode - In this mode, the file is opened for exclusive creation. If the file already exists, an error will be raised. If it doesn't exist, a new file will be created.
  5. 'b': Binary mode - This mode is used for binary files, such as images or executables. By adding the 'b' mode to any other mode (e.g., 'rb', 'wb', 'ab'), the file will be treated as a binary file.
  6. 't': Text mode - This mode is used for text files. By adding the 't' mode to any other mode (e.g., 'rt', 'wt', 'at'), the file will be treated as a text file. By default, if no mode is specified, Python assumes 't' mode.

You can combine modes to achieve the desired effect. For example, 'r+' opens a file for both reading and writing, while 'rb' opens a file for reading in binary mode.

Some common file operations include:

  1. read(): Read the entire content of the file as a single string (or as bytes in binary mode).
  2. readline(): Read a single line from the file.
  3. readlines(): Read all lines from the file into a list.
  4. write(): Write a string (or bytes in binary mode) to the file.
  5. writelines(): Write a list of strings (or bytes in binary mode) to the file.
  6. seek(): Move the file pointer to a specific position in the file.
  7. tell(): Get the current position of the file pointer.

Remember to close a file once you're done with it, either by calling the close() method or by using the with statement, which automatically closes the file when the block of code is exited. Properly closing a file ensures that any changes are saved and resources are released.

Here's a code example that demonstrates some of the file modes and operations we discussed in the previous explanation:

# Writing a file in write mode
with open("example.txt", "w") as f:
    f.write("This is an example file.\n")
    f.write("We are writing some content here.\n")

# Reading a file in read mode
with open("example.txt", "r") as f:
    content = f.read()
    print("Content of the file:")
    print(content)

# Appending content to the file in append mode
with open("example.txt", "a") as f:
    f.write("This line is appended to the file.\n")

# Reading the file again after appending
with open("example.txt", "r") as f:
    content = f.read()
    print("Content of the file after appending:")
    print(content)

# Demonstrating file operations
with open("example.txt", "r") as f:
    # Read a single line
    first_line = f.readline()
    print("First line:", first_line.strip())

    # Read all lines into a list
    f.seek(0)  # Move the file pointer back to the start of the file
    lines = f.readlines()
    print("All lines:", lines)

    # Get the current position of the file pointer
    position = f.tell()
    print("Current position of the file pointer:", position)

Output:

Content of the file:
This is an example file.
We are writing some content here.

Content of the file after appending:
This is an example file.
We are writing some content here.
This line is appended to the file.

First line: This is an example file.
All lines: ['This is an example file.\n', 'We are writing some content here.\n', 'This line is appended to the file.\n']
Current position of the file pointer: 82
To complete the next exercises, please visit cuantum.tech/books/python-beginner/chapter6/ and download the files required for each exercise.

Exercise 6.3.1: Counting Lines in a File

Create a program that reads a given file and prints the number of lines in the file.

Instructions:

  1. Read the provided "sample_text.txt" file.
  2. Count the number of lines in the file.
  3. Print the number of lines.

Solution code:

filename = "sample_text.txt"

with open(filename, "r") as f:
    lines = f.readlines()
    line_count = len(lines)

print(f"The number of lines in the file is: {line_count}")

Output:

The number of lines in the file is: 4

The "sample_text.txt" file has the following content:

This is a sample file.
It contains some text.
Here is another line.
And this is the last line.

Exercise 6.3.2: Copying a File

Create a program that reads a given file and creates a new file with its content.

Instructions:

  1. Read the provided "source.txt" file.
  2. Create a new file called "destination.txt" and write the content of "source.txt" into it.

Solution code:

source_filename = "source.txt"
destination_filename = "destination.txt"

with open(source_filename, "r") as source_file:
    content = source_file.read()

    with open(destination_filename, "w") as destination_file:
        destination_file.write(content)

print(f"Content from {source_filename} has been copied to {destination_filename}.")

Output:

Content from source.txt has been copied to destination.txt.

Exercise 6.3.3: Reading a Specific Line

Create a program that reads a given file and prints the content of a specific line number.

Instructions:

  1. Read the provided "lines.txt" file.
  2. Prompt the user to enter a line number.
  3. Print the content of the specified line.

Solution code:

filename = "lines.txt"

with open(filename, "r") as f:
    lines = f.readlines()

line_number = int(input("Enter the line number: "))
if 0 < line_number <= len(lines):
    print(f"Line {line_number}: {lines[line_number - 1].strip()}")
else:
    print("Invalid line number.")

Output (example):

Enter the line number: 2
Line 2: This is the second line.

The "lines.txt" file has the following content:

This is the first line.
This is the second line.
This is the third line.
This is the fourth line.

6.3: File Modes and Operations

When working with files in Python, it is essential to understand the different file modes and operations available. File modes determine how you can interact with a file (e.g., reading, writing, or appending), while file operations refer to the actions you perform on a file (e.g., reading content, writing content, or seeking a specific position). 

Here's a detailed explanation of common file modes:

  1. 'r': Read mode - In this mode, the file is opened for reading. You can only read the file's content, and the file must exist before opening. If the file doesn't exist, a FileNotFoundError will be raised.
  2. 'w': Write mode - In this mode, the file is opened for writing. If the file doesn't exist, it will be created. If it already exists, its content will be overwritten (i.e., truncated).
  3. 'a': Append mode - In this mode, the file is opened for appending. If the file doesn't exist, it will be created. If it already exists, new data will be added to the end of the file, preserving the original content. 
  4. 'x': Exclusive creation mode - In this mode, the file is opened for exclusive creation. If the file already exists, an error will be raised. If it doesn't exist, a new file will be created.
  5. 'b': Binary mode - This mode is used for binary files, such as images or executables. By adding the 'b' mode to any other mode (e.g., 'rb', 'wb', 'ab'), the file will be treated as a binary file.
  6. 't': Text mode - This mode is used for text files. By adding the 't' mode to any other mode (e.g., 'rt', 'wt', 'at'), the file will be treated as a text file. By default, if no mode is specified, Python assumes 't' mode.

You can combine modes to achieve the desired effect. For example, 'r+' opens a file for both reading and writing, while 'rb' opens a file for reading in binary mode.

Some common file operations include:

  1. read(): Read the entire content of the file as a single string (or as bytes in binary mode).
  2. readline(): Read a single line from the file.
  3. readlines(): Read all lines from the file into a list.
  4. write(): Write a string (or bytes in binary mode) to the file.
  5. writelines(): Write a list of strings (or bytes in binary mode) to the file.
  6. seek(): Move the file pointer to a specific position in the file.
  7. tell(): Get the current position of the file pointer.

Remember to close a file once you're done with it, either by calling the close() method or by using the with statement, which automatically closes the file when the block of code is exited. Properly closing a file ensures that any changes are saved and resources are released.

Here's a code example that demonstrates some of the file modes and operations we discussed in the previous explanation:

# Writing a file in write mode
with open("example.txt", "w") as f:
    f.write("This is an example file.\n")
    f.write("We are writing some content here.\n")

# Reading a file in read mode
with open("example.txt", "r") as f:
    content = f.read()
    print("Content of the file:")
    print(content)

# Appending content to the file in append mode
with open("example.txt", "a") as f:
    f.write("This line is appended to the file.\n")

# Reading the file again after appending
with open("example.txt", "r") as f:
    content = f.read()
    print("Content of the file after appending:")
    print(content)

# Demonstrating file operations
with open("example.txt", "r") as f:
    # Read a single line
    first_line = f.readline()
    print("First line:", first_line.strip())

    # Read all lines into a list
    f.seek(0)  # Move the file pointer back to the start of the file
    lines = f.readlines()
    print("All lines:", lines)

    # Get the current position of the file pointer
    position = f.tell()
    print("Current position of the file pointer:", position)

Output:

Content of the file:
This is an example file.
We are writing some content here.

Content of the file after appending:
This is an example file.
We are writing some content here.
This line is appended to the file.

First line: This is an example file.
All lines: ['This is an example file.\n', 'We are writing some content here.\n', 'This line is appended to the file.\n']
Current position of the file pointer: 82
To complete the next exercises, please visit cuantum.tech/books/python-beginner/chapter6/ and download the files required for each exercise.

Exercise 6.3.1: Counting Lines in a File

Create a program that reads a given file and prints the number of lines in the file.

Instructions:

  1. Read the provided "sample_text.txt" file.
  2. Count the number of lines in the file.
  3. Print the number of lines.

Solution code:

filename = "sample_text.txt"

with open(filename, "r") as f:
    lines = f.readlines()
    line_count = len(lines)

print(f"The number of lines in the file is: {line_count}")

Output:

The number of lines in the file is: 4

The "sample_text.txt" file has the following content:

This is a sample file.
It contains some text.
Here is another line.
And this is the last line.

Exercise 6.3.2: Copying a File

Create a program that reads a given file and creates a new file with its content.

Instructions:

  1. Read the provided "source.txt" file.
  2. Create a new file called "destination.txt" and write the content of "source.txt" into it.

Solution code:

source_filename = "source.txt"
destination_filename = "destination.txt"

with open(source_filename, "r") as source_file:
    content = source_file.read()

    with open(destination_filename, "w") as destination_file:
        destination_file.write(content)

print(f"Content from {source_filename} has been copied to {destination_filename}.")

Output:

Content from source.txt has been copied to destination.txt.

Exercise 6.3.3: Reading a Specific Line

Create a program that reads a given file and prints the content of a specific line number.

Instructions:

  1. Read the provided "lines.txt" file.
  2. Prompt the user to enter a line number.
  3. Print the content of the specified line.

Solution code:

filename = "lines.txt"

with open(filename, "r") as f:
    lines = f.readlines()

line_number = int(input("Enter the line number: "))
if 0 < line_number <= len(lines):
    print(f"Line {line_number}: {lines[line_number - 1].strip()}")
else:
    print("Invalid line number.")

Output (example):

Enter the line number: 2
Line 2: This is the second line.

The "lines.txt" file has the following content:

This is the first line.
This is the second line.
This is the third line.
This is the fourth line.

6.3: File Modes and Operations

When working with files in Python, it is essential to understand the different file modes and operations available. File modes determine how you can interact with a file (e.g., reading, writing, or appending), while file operations refer to the actions you perform on a file (e.g., reading content, writing content, or seeking a specific position). 

Here's a detailed explanation of common file modes:

  1. 'r': Read mode - In this mode, the file is opened for reading. You can only read the file's content, and the file must exist before opening. If the file doesn't exist, a FileNotFoundError will be raised.
  2. 'w': Write mode - In this mode, the file is opened for writing. If the file doesn't exist, it will be created. If it already exists, its content will be overwritten (i.e., truncated).
  3. 'a': Append mode - In this mode, the file is opened for appending. If the file doesn't exist, it will be created. If it already exists, new data will be added to the end of the file, preserving the original content. 
  4. 'x': Exclusive creation mode - In this mode, the file is opened for exclusive creation. If the file already exists, an error will be raised. If it doesn't exist, a new file will be created.
  5. 'b': Binary mode - This mode is used for binary files, such as images or executables. By adding the 'b' mode to any other mode (e.g., 'rb', 'wb', 'ab'), the file will be treated as a binary file.
  6. 't': Text mode - This mode is used for text files. By adding the 't' mode to any other mode (e.g., 'rt', 'wt', 'at'), the file will be treated as a text file. By default, if no mode is specified, Python assumes 't' mode.

You can combine modes to achieve the desired effect. For example, 'r+' opens a file for both reading and writing, while 'rb' opens a file for reading in binary mode.

Some common file operations include:

  1. read(): Read the entire content of the file as a single string (or as bytes in binary mode).
  2. readline(): Read a single line from the file.
  3. readlines(): Read all lines from the file into a list.
  4. write(): Write a string (or bytes in binary mode) to the file.
  5. writelines(): Write a list of strings (or bytes in binary mode) to the file.
  6. seek(): Move the file pointer to a specific position in the file.
  7. tell(): Get the current position of the file pointer.

Remember to close a file once you're done with it, either by calling the close() method or by using the with statement, which automatically closes the file when the block of code is exited. Properly closing a file ensures that any changes are saved and resources are released.

Here's a code example that demonstrates some of the file modes and operations we discussed in the previous explanation:

# Writing a file in write mode
with open("example.txt", "w") as f:
    f.write("This is an example file.\n")
    f.write("We are writing some content here.\n")

# Reading a file in read mode
with open("example.txt", "r") as f:
    content = f.read()
    print("Content of the file:")
    print(content)

# Appending content to the file in append mode
with open("example.txt", "a") as f:
    f.write("This line is appended to the file.\n")

# Reading the file again after appending
with open("example.txt", "r") as f:
    content = f.read()
    print("Content of the file after appending:")
    print(content)

# Demonstrating file operations
with open("example.txt", "r") as f:
    # Read a single line
    first_line = f.readline()
    print("First line:", first_line.strip())

    # Read all lines into a list
    f.seek(0)  # Move the file pointer back to the start of the file
    lines = f.readlines()
    print("All lines:", lines)

    # Get the current position of the file pointer
    position = f.tell()
    print("Current position of the file pointer:", position)

Output:

Content of the file:
This is an example file.
We are writing some content here.

Content of the file after appending:
This is an example file.
We are writing some content here.
This line is appended to the file.

First line: This is an example file.
All lines: ['This is an example file.\n', 'We are writing some content here.\n', 'This line is appended to the file.\n']
Current position of the file pointer: 82
To complete the next exercises, please visit cuantum.tech/books/python-beginner/chapter6/ and download the files required for each exercise.

Exercise 6.3.1: Counting Lines in a File

Create a program that reads a given file and prints the number of lines in the file.

Instructions:

  1. Read the provided "sample_text.txt" file.
  2. Count the number of lines in the file.
  3. Print the number of lines.

Solution code:

filename = "sample_text.txt"

with open(filename, "r") as f:
    lines = f.readlines()
    line_count = len(lines)

print(f"The number of lines in the file is: {line_count}")

Output:

The number of lines in the file is: 4

The "sample_text.txt" file has the following content:

This is a sample file.
It contains some text.
Here is another line.
And this is the last line.

Exercise 6.3.2: Copying a File

Create a program that reads a given file and creates a new file with its content.

Instructions:

  1. Read the provided "source.txt" file.
  2. Create a new file called "destination.txt" and write the content of "source.txt" into it.

Solution code:

source_filename = "source.txt"
destination_filename = "destination.txt"

with open(source_filename, "r") as source_file:
    content = source_file.read()

    with open(destination_filename, "w") as destination_file:
        destination_file.write(content)

print(f"Content from {source_filename} has been copied to {destination_filename}.")

Output:

Content from source.txt has been copied to destination.txt.

Exercise 6.3.3: Reading a Specific Line

Create a program that reads a given file and prints the content of a specific line number.

Instructions:

  1. Read the provided "lines.txt" file.
  2. Prompt the user to enter a line number.
  3. Print the content of the specified line.

Solution code:

filename = "lines.txt"

with open(filename, "r") as f:
    lines = f.readlines()

line_number = int(input("Enter the line number: "))
if 0 < line_number <= len(lines):
    print(f"Line {line_number}: {lines[line_number - 1].strip()}")
else:
    print("Invalid line number.")

Output (example):

Enter the line number: 2
Line 2: This is the second line.

The "lines.txt" file has the following content:

This is the first line.
This is the second line.
This is the third line.
This is the fourth line.

6.3: File Modes and Operations

When working with files in Python, it is essential to understand the different file modes and operations available. File modes determine how you can interact with a file (e.g., reading, writing, or appending), while file operations refer to the actions you perform on a file (e.g., reading content, writing content, or seeking a specific position). 

Here's a detailed explanation of common file modes:

  1. 'r': Read mode - In this mode, the file is opened for reading. You can only read the file's content, and the file must exist before opening. If the file doesn't exist, a FileNotFoundError will be raised.
  2. 'w': Write mode - In this mode, the file is opened for writing. If the file doesn't exist, it will be created. If it already exists, its content will be overwritten (i.e., truncated).
  3. 'a': Append mode - In this mode, the file is opened for appending. If the file doesn't exist, it will be created. If it already exists, new data will be added to the end of the file, preserving the original content. 
  4. 'x': Exclusive creation mode - In this mode, the file is opened for exclusive creation. If the file already exists, an error will be raised. If it doesn't exist, a new file will be created.
  5. 'b': Binary mode - This mode is used for binary files, such as images or executables. By adding the 'b' mode to any other mode (e.g., 'rb', 'wb', 'ab'), the file will be treated as a binary file.
  6. 't': Text mode - This mode is used for text files. By adding the 't' mode to any other mode (e.g., 'rt', 'wt', 'at'), the file will be treated as a text file. By default, if no mode is specified, Python assumes 't' mode.

You can combine modes to achieve the desired effect. For example, 'r+' opens a file for both reading and writing, while 'rb' opens a file for reading in binary mode.

Some common file operations include:

  1. read(): Read the entire content of the file as a single string (or as bytes in binary mode).
  2. readline(): Read a single line from the file.
  3. readlines(): Read all lines from the file into a list.
  4. write(): Write a string (or bytes in binary mode) to the file.
  5. writelines(): Write a list of strings (or bytes in binary mode) to the file.
  6. seek(): Move the file pointer to a specific position in the file.
  7. tell(): Get the current position of the file pointer.

Remember to close a file once you're done with it, either by calling the close() method or by using the with statement, which automatically closes the file when the block of code is exited. Properly closing a file ensures that any changes are saved and resources are released.

Here's a code example that demonstrates some of the file modes and operations we discussed in the previous explanation:

# Writing a file in write mode
with open("example.txt", "w") as f:
    f.write("This is an example file.\n")
    f.write("We are writing some content here.\n")

# Reading a file in read mode
with open("example.txt", "r") as f:
    content = f.read()
    print("Content of the file:")
    print(content)

# Appending content to the file in append mode
with open("example.txt", "a") as f:
    f.write("This line is appended to the file.\n")

# Reading the file again after appending
with open("example.txt", "r") as f:
    content = f.read()
    print("Content of the file after appending:")
    print(content)

# Demonstrating file operations
with open("example.txt", "r") as f:
    # Read a single line
    first_line = f.readline()
    print("First line:", first_line.strip())

    # Read all lines into a list
    f.seek(0)  # Move the file pointer back to the start of the file
    lines = f.readlines()
    print("All lines:", lines)

    # Get the current position of the file pointer
    position = f.tell()
    print("Current position of the file pointer:", position)

Output:

Content of the file:
This is an example file.
We are writing some content here.

Content of the file after appending:
This is an example file.
We are writing some content here.
This line is appended to the file.

First line: This is an example file.
All lines: ['This is an example file.\n', 'We are writing some content here.\n', 'This line is appended to the file.\n']
Current position of the file pointer: 82
To complete the next exercises, please visit cuantum.tech/books/python-beginner/chapter6/ and download the files required for each exercise.

Exercise 6.3.1: Counting Lines in a File

Create a program that reads a given file and prints the number of lines in the file.

Instructions:

  1. Read the provided "sample_text.txt" file.
  2. Count the number of lines in the file.
  3. Print the number of lines.

Solution code:

filename = "sample_text.txt"

with open(filename, "r") as f:
    lines = f.readlines()
    line_count = len(lines)

print(f"The number of lines in the file is: {line_count}")

Output:

The number of lines in the file is: 4

The "sample_text.txt" file has the following content:

This is a sample file.
It contains some text.
Here is another line.
And this is the last line.

Exercise 6.3.2: Copying a File

Create a program that reads a given file and creates a new file with its content.

Instructions:

  1. Read the provided "source.txt" file.
  2. Create a new file called "destination.txt" and write the content of "source.txt" into it.

Solution code:

source_filename = "source.txt"
destination_filename = "destination.txt"

with open(source_filename, "r") as source_file:
    content = source_file.read()

    with open(destination_filename, "w") as destination_file:
        destination_file.write(content)

print(f"Content from {source_filename} has been copied to {destination_filename}.")

Output:

Content from source.txt has been copied to destination.txt.

Exercise 6.3.3: Reading a Specific Line

Create a program that reads a given file and prints the content of a specific line number.

Instructions:

  1. Read the provided "lines.txt" file.
  2. Prompt the user to enter a line number.
  3. Print the content of the specified line.

Solution code:

filename = "lines.txt"

with open(filename, "r") as f:
    lines = f.readlines()

line_number = int(input("Enter the line number: "))
if 0 < line_number <= len(lines):
    print(f"Line {line_number}: {lines[line_number - 1].strip()}")
else:
    print("Invalid line number.")

Output (example):

Enter the line number: 2
Line 2: This is the second line.

The "lines.txt" file has the following content:

This is the first line.
This is the second line.
This is the third line.
This is the fourth line.