所以,我的代码是:
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
我希望程序只打印第一行,但我不想删除第二行。这可能吗?
答案 0 :(得分:0)
在第一次迭代之后打破循环...
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
答案 1 :(得分:0)
决定不打印与删除非常不同。你可以这样做:
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)