'Replace the 3's column as shown in the picture into an increment counter in python
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
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())
Solution 1:[1]
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
Solution 2:[2]
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
| Solution 2 | Tim |
