Learning how to write to a specific line in a file is a useful skill when dealing with text files in Python. This tutorial will walk you through the necessary steps and techniques to accomplish this task.
Step 1: Read the File
First, you need to read the existing file. Open the file in reading mode using the open() function and read all the lines into a list.
1 2 3 |
file = open('filename.txt', 'r') lines = file.readlines() file.close() |
Step 2: Modify the Specific Line
In order to modify a specific line, you need to reference it by its index number in the list. Python lists use zero-based indexing, which means the first line is index 0, the second line is index 1, and so on.
1 |
lines[line_number_to_modify] = 'New text\n' |
Step 3: Write Back to the File
After modifying the specific line, the changes must be written back to the file. Open the file in write mode and write the lines from the list back to the file.
1 2 3 |
file = open('filename.txt', 'w') file.writelines(lines) file.close() |
Implementing the Steps Together
Here is how to put all these steps together:
1 2 3 4 5 6 7 8 9 10 |
def modify_line(filename, line_num, text): file = open(filename, 'r') lines = file.readlines() file.close() lines[line_num] = text + '\n' file = open(filename, 'w') file.writelines(lines) file.close() |
Generated File Content
Assuming we have a file filename.txt with the following content:
Hello World This is a test Python is fun
We call our function with parameters as follows:
1 |
modify_line('filename.txt', 1, 'This is an edited line') |
Expected Output
The file filename.txt should now have the following content:
Hello World This is an edited line Python is fun
Full Code
Here is the complete Python code from this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def modify_line(filename, line_num, text): file = open(filename, 'r') lines = file.readlines() file.close() lines[line_num] = text + '\n' file = open(filename, 'w') file.writelines(lines) file.close() # example usage modify_line('filename.txt', 1, 'This is an edited line') |
Conclusion
In this tutorial, we learned how to read from a file, modify a specific line, and write the changes back to the file using Python. This can be a powerful technique for file processing and manipulation in many Python applications.
Keep practicing and exploring other built-in Python functions to enhance your data-handling skills.