TransWikia.com

Python: overwrite text file - string placeholder

Stack Overflow Asked by thommy bee on January 28, 2021

How do I use (if they exist) string placeholders for writing in a text file?
I want to write a text file, which keeps track of how many lines are written in itself. As soon as the amount of lines changes, the count should change accordingly.

Here is an example:

number_of_lines = 0

with open('./test.txt', "w") as out_file:
    out_file.write('number of elements in list: '+str(2)+'n')
    out_file.write('element 1n')
    out_file.write('element 2n')

with open('./test.txt', "r+") as out_file:
    next(out_file)
    out_file.write('element 3n')
    out_file.write('element 4n') 
    out_file.write('element 5n')
    out_file.write('element 6n') 
    out_file.write('element 7n')
    out_file.write('element 8n') 
    out_file.write('element 9n')
    out_file.write('element 10n')    # now 2 Digits '10'
    out_file.seek(0)
    for i in out_file:
        number_of_lines += 1
    
    out_file.seek(0)
    out_file.write('number of elements in list: '+str(number_of_lines-1)+'n')

text file:

number of elements in list: 10
lement 1
element 2
element 3
element 4
element 5
element 6
element 7
element 8
element 9
element 10

One Answer

As a .txt file can't read itself, the tricky part in what you are trying to do is updating only a specific line in a file while keeping the rest of the data. More on that here.

So, a simple solution would be to define a function to update the relevant line, then call it after each modification we make to the file. Let's do that:

def update_line_count(filename):
    with open(filename, 'r') as original:
        # Get the original file data so we can re-insert it later
        data = original.read()
    with open(filename, 'w') as modified:
        # Remove the first line if it's already a line count
        if data.startswith('number of elements in list'):
            data = 'n'.join(data.split('n')[1:])
        # Get the updated line count
        number_of_lines = len(data.split('n'))-1
        updated = f'number of elements in list: {number_of_lines}n{data}'
        modified.write(updated)

Now we can just call it after we make modifications to the file, and it will update the first line to include the correct line count.

Let's see it in action:

my_file = './test.txt'

with open(my_file, "w") as file:
    file.write('element 1n')
    file.write('element 2n')

update_line_count(my_file)

Now, inside test.txt, we have:

number of elements in list: 2
element 1
element 2

Let's modify and update some more:

with open(my_file, "r+") as file:
    next(file)
    file.write('element 3n')
    file.write('element 4n') 
    file.write('element 5n')
    file.write('element 6n') 
    file.write('element 7n')
    file.write('element 8n') 
    file.write('element 9n')
    file.write('element 10n')
    file.write('element 100n')
    file.write('element 1000?n')

update_line_count(my_file)

Look inside test.txt:

number of elements in list: 12
element 1
element 2
element 3
element 4
element 5
element 6
element 7
element 8
element 9
element 10
element 100
element 1000?

Hooray! :)

Answered by pitamer on January 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP