Python noob using 2.7 on Windows. I’m working on making a hierarchy tree view in HTML programatically. I’ve got a file that is outputted similar to this:
0
2
4
6
8
8
0
2
4
4
6
8
8
6
6
out.txt looks like this:
0
2
4
6
8
8
0
2
4
4
4
6
8
8
6
6
My code:
x = open('out.txt','r')
for current_line in x:
prev_line = current_line[:-1]
print "Current: " + current_line
print "Previous: " + prev_line
if prev_line > current_line:
print "Folder"
elif prev_line == current_line:
print "Root"
x.close()
The problem I’m encountering is that each time I try to compare the prev_line to the current_line I do not get the desired output. I can do something like if prev_line == "0": print "Root" but that will not work as it is for only that case. Also, it seems like the if portion is being calculated before the next current is done. The results that I get from my current code includes:
Current: 0
Previous: 0
Current: 2
Previous: 2
Current: 4
Previous: 4
Current: 6
Previous: 6
Current: 8
Previous: 8
Current: 8
Previous: 8
Current: 0
Previous: 0
Current: 2
Previous: 2
Current: 4
Previous: 4
Current: 4
Previous: 4
Current: 4
Previous: 4
Current: 6
Previous: 6
Current: 8
Previous: 8
Current: 8
Previous: 8
Current: 6
Previous: 6
Current: 6
Previous:
What am I doing wrong and how do I fix this? I don’t know if this is a string vs int comparison but if it is I’m gonna feel dumb. I’ve tried it but it raises an error when checking the last “Previous:”.
Set prev_line to the value of current_line at the end of the for loop.