How to Modify a Text File in Python?

Summary: You can modify a text file in Python using one of the following methods:

  • Using The seek() Method
  • Using The fileinput Module
  • Using The splitlines() Method
  • Using the regex module and the split() and insert() methods

Overview

Problem: Given a text file; how to modify it in Python?

Scenario 1: Insert a New Line in The File

Consider that you have the following text file that lists certain websites and you want to insert another website (string) in a new-line into the file.

Given file:

You intend to insert, “Freelancer.com” in the list given in the above file without deleting the file.

Scenario 2: Insert a New Sentence in The Same Line

In the previous example, you wanted to insert a string in a new line, what if you want to insert a new string at a certain place in a paragraph irrespective of the lines. For example, you have a file with the following sentences as shown below:

Peter Piper picked a peck of pickled peppers.A peck of pickled peppers Peter Piper picked.Wheres the peck of pickled peppers Peter Piper picked.

You want to insert a new sentence (for example – If Peter Piper picked a peck of pickled peppers) after the second sentence. So, the desired output is:

Peter Piper picked a peck of pickled peppers.A peck of pickled peppers Peter Piper picked.If Peter Piper picked a peck of pickled peppers.Wheres the peck of pickled peppers Peter Piper picked.

So, how are you going to accomplish the above tasks? ?

Before we proceed further please note that:

You cannot insert a string into the middle of a file without re-writing it. You can append to a file or overwrite part of it using the seek() method which we will dive into in a while; but if you wish to add something at the beginning or the middle of the file, you will have to rewrite it. As simple as that! ? This is completely an operating system thing and has nothing to do with Python. This is the case in all languages.

Therefore, the best practice is:

  • read from the file,
  • make the necessary modifications,
  • write it out to a new file ( for example ‘my_file.txt.tmp’). This is far better than reading the entire file into the memory, especially if the file is large.
  • Once the temporary file is completed, rename it to the same name as the original file.

This is an effective and safe way to do it because if for any reason the file write crashes or aborts then you still have your untouched original file.

Now that we have a clear understanding of the problem and the right approach to make the modifications, let us dive into the solutions and find out how we can implement our concept in Python!

Solutions to Scenario 1

❒ Method 1: Using The seek() Method

⁕ Definition and Usage of the seek() Method

seek() is a Python file method that allows you set the current file position in a file stream. It also returns the new position.

Syntax:

Let’s use the seek() method to modify our file.

⁕ The Solution

Case 1: Appending to the middle of the file.

with open('test.txt', 'r+') as f:
    file = f.readlines()
    for line in file:
        if 'Upwork' in line:
            pos = line.index('Upwork')
            file.insert(pos + 1, 'Freelancer.com\n')
    f.seek(0)
    f.writelines(file)
f.close()

Output:

Case 2: Prepending to the End of file

If you just want to append to the file then all you have to do is open up the file in append mode and insert the required string.

with open('test.txt', 'a') as f:
    f.write('\nFreelancer.com')

Output:

Case 3: Prepending to the Beginning of the File

with open('test.txt', 'r+') as f:
    file = f.readlines()
    file.insert(0,'Freelancer.com\n')
    f.seek(0)
    f.writelines(file)

Output

❒ Method 2: Using The fileinput Module

Another workaround to modify a file is that you can use the fileinput module of the Python standard library that allows you to rewrite a file by setting the inplace keyword argument as inplace=true.

import fileinput

f = fileinput.input('test.txt', inplace=true)
for n, line in enumerate(f, start=1):
    if line.strip() == 'Finxter':
        print('Freelancer.com')
    print(line, end='')

Output:

❒ Method 3: Using The splitlines() Method

❖ splitlines() is method in Python which is used to split a string breaking at line boundaries. It returns a list of the lines, breaking at line boundaries.

with open('test.txt', 'r+') as infile:
    data = infile.read()  # Read the contents of the file into memory.
    # Return a list of the lines, breaking at line boundaries.
    li = data.splitlines()
    index = li.index('Upwork')+1
    li.insert(index,'Freelancer.com')
    infile.seek(0)
    for item in li:
        infile.writelines(item+'\n')

Output:

The Solution to Scenario 2

Now let us have a quick look at the solution to our second scenario wherein we will be inserting a new sentence, irrespective of the line number. A simple solution to this problem is to split the sentences with full-stop as the separator and also store the separator along with the texts. Then you can insert the additional sentence in the required space and finally write it to the file.

import re

f = open("demo.txt", "r+")
contents = f.read()
text = re.split('([.])', contents)
text.insert(4, 'If Peter Piper picked a peck of pickled peppers.')
f.seek(0)
f.writelines(text)
f.close()

Output:

Peter Piper picked a peck of pickled peppers.A peck of pickled peppers Peter Piper picked.If Peter Piper picked a peck of pickled peppers.Wheres the peck of pickled peppers Peter Piper picked.

You might want to have a look at another scenario described in the following post:

How to Search and Replace a Line in a File in Python?

Conclusion

In this article we discussed how to modify a file in Python with the help of a couple of scenarios. We used the following ways to reach our final solution:

With that, we come to the end of this article and I hope you can modify files in Python with ease after reading this article! Please stay tuned and subscribe for more interesting articles and discussions.

🌍 Related Tutorial: Python – How to Update and Replace Text in a File

If you want to edit a text file in Windows PowerShell, feel free to check out this detailed article on the Finxter blog.