如何在python中每次从文本文件中打印某些行

时间:2016-02-21 20:35:49

标签: python

我不知道如何从文本文件中打印某些代码行。当我运行下面的代码时,它什么也没做。如何读取文件中的特定行?。

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()

我的输出可以是随机字符串,我不介意,只要它只打印一组行。

2 个答案:

答案 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