簡體   English   中英

從python輸出的變量中輸出最后一行

[英]print last line from the variable output in python

我正在尋找從line變量產生的最后一行

bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line

我得到的輸出如下。

-122.1058
-123.1050
-125.10584323

我想要打印的結果是

-125.10584323

而且,我從一些咯咯地笑聲中得到了提示,並獲得了期望的輸出,但這一點對我來說似乎有點復雜。

bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)

希望以此為繼。

bash-4.1$ ./file2_dup.py
-125.10584323

PS:我只是出於以下目的而借用了這個問題: 如何使用python讀取特定行並在該行中打印特定位置

您可以像這樣測試新行是否小於之前的行

#!/usr/bin/python
res_line = 0
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = float(line.split()[-1].strip())
      if res_line > line:
          res_line = line
  print res_line

編輯:

您可以使用enumerate()獲取循環中索引的行:

with open("file1.txt", "rt") as f:
    lines = f.readlines()
    for line, content in enumerate(lines):
        # apply your logic to line and/or content here
        # by adding ifs to select the lines you want...
        print line, content.strip() # do your thing

將會輸出(只是為了說明,因為我沒有在上面的代碼中指定任何條件):

0 -122.1058
1 -123.1050
2 -125.10584323
3 

或者通過使用以下代碼在listcomp中選擇帶有條件的特定行:

with open("file1.txt", "rt") as f:
    lines = f.readlines()
    result = [ content.strip() for line, content in enumerate(lines)
         if line == len(lines) - 2] # creates a list with
                                    # only the last line
    print result[0]

將輸出:

-125.10584323

請嘗試以下操作:

print [line.split()[-1].strip() for line in lines if '!' in line][-1]

我看到了一種更好的方法,即創建一個空列表並附加條件中的值,然后選擇您所選擇的索引並列出輸出,從某種意義上講,它可以用於您所感興趣的任何行,這是一個好方法需要選擇。

讓我們假設我要倒數第二行,那么可以將該值放到打印部分print(lst[-2]) ,它將打印第二行的最后一個索引。

#!/usr/bin/python
file = open('file1.txt', 'r')
lst = list()
for line in file:
    if "!" in line:
        x= line.split()
        lst.append(x[-1])

print(lst[-1])

暫無
暫無

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

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