在Windows上使用2.7的Python noob。我正在以编程方式在HTML中创建层级树视图。我有一个输出类似于这样一个文件:Python:读取上一行并与当前行进行比较
0
2
4
6
8
8
0
2
4
4
6
8
8
6
6
out.txt看起来是这样的:
0
2
4
6
8
8
0
2
4
4
4
6
8
8
6
6
我的代码:
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()
我现在遇到的问题是,每次我尝试将prev_line与current_line比较时,我都没有得到所需的输出。我可以做类似if prev_line == "0": print "Root"的事情,但那不会起作用,因为它仅适用于这种情况。此外,似乎在下一个电流完成之前正在计算if部分。我从当前代码得到的结果包括:
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:
我在做什么错,我该如何解决这个问题?我不知道这是一个字符串还是int比较,但如果是这样的话,我会感觉到愚蠢。我试过了,但是在检查最后一个“Previous:”时会引发错误。
2012-01-04
serk