Python - Reading and Writing Files

9.
How can you iterate through lines in a file using a for loop?

To iterate through lines in a file using a for loop in Python, you can use the file object directly. The file object is iterable, and each iteration of the loop corresponds to reading a line from the file. Here's an example program that demonstrates how to iterate through lines in a file using a for loop:

# Open the file in read mode
with open('example.txt', 'r') as file:
    # Iterate through lines using a for loop
    for line in file:
        print("Line:", line.strip())

In this example, the file 'example.txt' is opened in read mode using the with statement. The for loop is used to iterate through the lines in the file. The strip() method is used to remove leading and trailing whitespaces, including the newline character, from each line.

The output of the program will be:

Line: This is the first line.
Line: This is the second line.
Line: This is the third line.

10.
Discuss the use of the write() method for writing to a file.

In Python, the write() method is used for writing data to a file. The method takes a string as an argument and writes it to the file at the current position of the file pointer. If the file does not exist, it creates a new file with the specified name. If the file already exists and is opened in write mode ('w'), it truncates the file to zero length before writing.

Here's an example program that demonstrates the use of the write() method to write content to a file:

# Open the file in write mode
with open('new_file.txt', 'w') as file:
    # Write content to the file
    file.write("This is the first line.\n")
    file.write("This is the second line.\n")
    file.write("This is the third line.\n")

# Read the contents of the written file
with open('new_file.txt', 'r') as read_file:
    content = read_file.read()
    print("File Content:")
    print(content)

In this example, the file 'new_file.txt' is opened in write mode using the with statement. The write() method is then used to write three lines of text to the file. Finally, the contents of the written file are read and printed to verify the successful writing operation.

The output of the program will be:

File Content:
This is the first line.
This is the second line.
This is the third line.

11.
Explain the difference between write() and writelines() methods.

In Python, both write() and writelines() methods are used for writing data to a file, but there are differences in how they handle input.

write() Method: The write() method takes a single string argument and writes the entire string to the file at the current position of the file pointer. It does not automatically add newline characters, so if you want to write multiple lines, you need to include newline characters explicitly.

# Open the file in write mode
with open('write_example.txt', 'w') as file:
    file.write("This is the first line.\n")
    file.write("This is the second line.\n")
    file.write("This is the third line.\n")
writelines() Method: The writelines() method takes an iterable (e.g., a list of strings) as an argument and writes each element of the iterable to the file. It does not add newline characters between the elements, so if you want to separate lines, you need to include newline characters explicitly.

# Open the file in write mode
with open('writelines_example.txt', 'w') as file:
    lines = ["This is the first line.", "This is the second line.", "This is the third line."]
    file.writelines(line + '\n' for line in lines)

In both examples, the file is opened in write mode, and content is written using either the write() or writelines() method. The with statement is used to ensure that the file is properly closed after writing.

The outputs of the programs will be:

Contents of 'write_example.txt':
This is the first line.
This is the second line.
This is the third line.

Contents of 'writelines_example.txt':
This is the first line.
This is the second line.
This is the third line.

12.
How do you append data to an existing file in Python?

To append data to an existing file in Python, you can use the 'a' mode when opening the file. The 'a' mode stands for append, and it allows you to add content to the end of the file without truncating the existing content. Here's an example program that demonstrates how to append data to an existing file:

# Open the file in append mode
with open('existing_file.txt', 'a') as file:
    # Append content to the file
    file.write("This is new content appended to the file.\n")

# Read the contents of the updated file
with open('existing_file.txt', 'r') as read_file:
    content = read_file.read()
    print("Updated File Content:")
    print(content)

In this example, the file 'existing_file.txt' is opened in append mode using the with statement. The write() method is then used to append a new line of content to the file. Finally, the contents of the updated file are read and printed to verify the successful appending operation.

The output of the program will be:

Updated File Content:
This is the existing content of the file.
This is new content appended to the file.