Home > Net >  Replace the 3's column as shown in the picture into an increment counter in python
Replace the 3's column as shown in the picture into an increment counter in python

Time:06-07

i want to replace the 3's column as shown in the picture into an increment counter. I tried using replace but the output is not what i expected

picture data

Here is my code:

lines = open('test1.txt', 'r').readlines()[2:]

count=0

for line in lines:

count =1

line=line.replace(line.split("  ")[1],str(count))

print(line.rstrip())

CodePudding user response:

You're always going to replace the final column, right? No need to use replace. Just use split and keep the first one.

count = 0
lines = open('test1.txt', 'r')
for line in lines:
    if not line[0].isdigit():
        continue
    parts = line.split()
    print(parts[0], count)
    count  = 1

CodePudding user response:

lines = open('test.txt', 'r').readlines()

count = 0;

with open('test.txt', 'w') as f:

    for x in lines:
        
        count =1
        
        line = x.split(" ")
        f.write(line[0]   " "   str(count)   "\n")
  • Related