我不知道如何从文本文件中打印某些代码行。当我运行下面的代码时,它什么也没做。如何读取文件中的特定行?。
line = open ("random.txt",2)
print(line)
line = open ("random.txt",5)
print(line)
line = open ("random.txt",7)
print(line)
line = open ("random.txt",9)
print(line)
line = open ("random.txt",10)
print(line)
myFile.close()
我的输出可以是随机字符串,我不介意,只要它只打印一组行。
答案 0 :(得分:1)
open
将模式作为其第二个参数,而不是数字。我想你需要的是:
with open("random.txt") as open_file:
lines = open_file.readlines()
print(lines[2])
print(lines[5])
...
with
块将负责关闭文件。
答案 1 :(得分:0)
wanted_lines = [2,5,7,9,10]
count = 1
with open('random.txt', 'r') as infile:
for line in infile:
line = line.strip()
if count in wanted_lines:
print(line)
else:
pass
count += 1