Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running replace() method in a for loop?

Its late and I have been trying to work on a simple script to rename point cloud data to a working format. I dont know what im doing wrong as the code at the bottom works fine. Why doesnt the code in the for loop work? It is adding it to the list but its just not getting formatted by the replace function. Sorry I know this isnt a debugger but I am really stuck on this and it would probably take 2 seconds for someone else to see the problem.

# Opening and Loading the text file then sticking its lines into a list []
filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
lines = text.readlines()
linesNew = []
temp = None


# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp.replace(' ', ', ',2)
    linesNew.append(temp)


# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)


text.close()
like image 838
SacredGeometry Avatar asked Oct 18 '11 23:10

SacredGeometry


1 Answers

Your not assigning the return value of replace() to anything. Also, readlines and str(i) are unnecessary.

Try this:

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
like image 178
chown Avatar answered Sep 28 '22 02:09

chown