簡體   English   中英

文件中特定行的 Python 輸出

[英]Python output from a specific line in a file

我有一個 txt 文件,每一行都有一個數字(第 1 行 = 1,第 2 行 = 2 等)。 我想用 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

一種方法是使用readlines 這個問題已經在Read specific lines only (Python) 中得到了回答,下次嘗試做一些搜索:P

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而不是1 這就是我們使用索引 0 和 2 獲取它的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM