如何停止打印行?

How to stop print lines?

所以,我的代码是:

file = open("save_file.txt")

for each_line in file:
    s = {}
    (s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = each_line.split(";")
    print(s['name'])
    print(s['race'])
    print(s['class'])
    print(s['FOR'])
    print(s['INT'])
    print(s['DES'])
file.close()

save_file.txt:

Nome: d;Raça: Humano;Classe: Mago;FOR: 5;INT: 7;DES: 5
Nome: g;Raça: umano;Classe: Mo;FOR: 56;INT: 47;DES: 85

我希望程序只打印第一行,但我不想删除第二行。这可能吗?

在第一次迭代后打破循环就这样...

for each_line in file:
    s = {}
    (s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = each_line.split(";")
    print(s['name'])
    print(s['race'])
    print(s['class'])
    print(s['FOR'])
    print(s['INT'])
    print(s['DES'])
    break

决定不打印与删除有很大不同。你可以这样做:

with open("save_file.txt") as f:
    for each_line in f:
        s = {}
        (s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = each_line.split(";")
        print(s['name'])
        print(s['race'])
        print(s['class'])
        print(s['FOR'])
        print(s['INT'])
        print(s['DES'])
        break  #<---

当遇到 break 时,它会跳出 for 循环,它只会从文件中打印一行。

此外,这使用 with 上下文管理器来避免以后必须显式关闭文件。


编辑

# Read all lines into lines list, each element is a dictionary
lines = []
with open("save_file.txt") as f:
    for line in f:
        s = {}
        (s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = line.split(";")
        lines.append(s)

# Print first line
s = lines[0]
print(s['name'])
print(s['race'])
print(s['class'])
print(s['FOR'])
print(s['INT'])
print(s['DES'])

# Print second line
s = lines[1]
print(s['name'])
print(s['race'])
print(s['class'])
print(s['FOR'])
print(s['INT'])
print(s['DES'])

# Or with a Function
def print_line(lines, num):
    s = lines[num]
    print(s['name'])
    print(s['race'])
    print(s['class'])
    print(s['FOR'])
    print(s['INT'])
    print(s['DES'])

# Print third line
print_line(lines, 2)