Python输出文件中的特定行

时间:2017-12-29 15:55:43

标签: python file

我有一个txt文件,每行都有一个数字(第1行= 1,第2行= 2等)。 The file I want to read in Python

我想在python(1 + 3)中添加第1行和第3行。我怎么能这样做?

我试过了:

    file = open(“example.txt”,”r”) 

    line1 = file.read('line 1') 
    line3 = file.read('line 3')

    file.close() 


result = line1 + line3

1 个答案:

答案 0 :(得分:0)

一种方法是使用>。此问题已在Reading specific lines only (Python)中得到解答。请尝试下次进行搜索:P

readlines

在许多编程语言中,索引从with open(“example.txt”,”r”) as f: lines = f.readlines() # this will gets all the lines at once line1 = lines[0] # get the first line line3 = lines[2] # get the third line result_int = int(line1) + int(line3) # if you are doing integer addtion. -> 3 result_str = line1 + line3 # will give you: 13 开始,而不是0。这就是我们使用索引0和2获取它的原因。