Number each line (in the middle) of a text file

Question:

I have a text file like this:

|DeviceImage|number|DeviceName
|DeviceImage|number|DeviceName
|DeviceImage|number|DeviceName
|DeviceImage|number|DeviceName

And I have the following code to number each line:

with open("test.txt", 'r') as readFile:
    content = readFile.read()
    contentList = content.split("n")
    count = 0

    for content in contentList:
        count += 1
        print(f"[{count}]: {content}")

Now, the problem is, the result is like this:

[1]: |DeviceImage|number|DeviceName
[2]: |DeviceImage|number|DeviceName
[3]: |DeviceImage|number|DeviceName
[4]: |DeviceImage|number|DeviceName

How can I replace the number in each line in the text file? Basically, All I want is to number each line where the number is, Line this:

|DeviceImage|1|DeviceName
|DeviceImage|2|DeviceName
|DeviceImage|3|DeviceName
|DeviceImage|4|DeviceName
Asked By: user15109593

||

Answers:

Simple solution:

with open("test.txt", 'r') as readFile:
    content = readFile.read()
    contentList = content.split("n")
    count = 0

    for content in contentList:
        count += 1
        splt = content.split("|")
        splt[2] = count
        print("|".join(splt))

Split by ‘|’ and just parse out the middle string to replace with count

Answered By: walker

If you only need to print your target output you can do this,

for content in contentList:
    count += 1
    print(f"[{count}]: {content.replace('number', str(count))}")

For actually modifying the file, open it in ‘r+’ mode and, with the same statement you can write it in the file. This should work,

with open("test.txt", 'r+') as readFile:
    content = readFile.read()
    contentList = content.split("n")
    count = 0
    readFile.seek(0)
    readFile.truncate()
    for content in contentList:
        count += 1
        readFile.write(content.replace('number', str(count)))
        readFile.write('n')
Answered By: Kunjan Rana
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.