簡體   English   中英

如何不打印最后一行

[英]How to not print the last line

我是python的新手。 我希望我的腳本打印除最后一行之外的所有內容。 我嘗試了[:-1],但我無法讓它工作。 我知道下面的代碼不是完美的,因為它是我的第一個,但它做了我需要它做的所有事情...我不希望它打印字符串的最后一行。 請幫忙

import requests


html = requests.get("")

html_str = html.content
Html_file= open("fb_remodel.csv",'a')
html_str = html_str.replace('},', '},\n')
html_str = html_str.replace(':"', ',')
html_str = html_str.replace('"', '')
html_str = html_str.replace('T', ' ')
html_str = html_str.replace('+', ',')
html_str = html_str.replace('_', ',')
Html_file.write(html_str[:-1])
Html_file.close()

html_str是一個字符串,而不是列表。

你可以這樣做:

txt='''\
Line 1
line 2
line 3
line 4
last line'''

print txt.rpartition('\n')[0]

要么

print txt.rsplit('\n',1)[0]

rpartitionrsplit之間的差異可以在文檔中看到。 如果在目標字符串中找不到拆分字符,我會根據我想要發生的事情在一個或另一個之間做出選擇。

順便說一下,您可能希望以這種方式打開文件:

with open("fb_remodel.csv",'a') as Html_file:
    # blah blah
    # at the end -- close is automatic.  

使用with是一種非常常見的Python習語。

如果你想要一個刪除最后n行的一般方法,這將做到這一點:

首先創建一個測試文件:

# create a test file of 'Line X of Y' type
with open('/tmp/lines.txt', 'w') as fout:      
    start,stop=1,11
    for i in range(start,stop):
        fout.write('Line {} of {}\n'.format(i, stop-start))

然后你可以使用deque are循環並執行一個動作:

from collections import deque

with open('/tmp/lines.txt') as fin:
    trim=6                              # print all but the last X lines
    d=deque(maxlen=trim+1)
    for line in fin:
        d.append(line)
        if len(d)<trim+1: continue
        print d.popleft().strip()

打印:

Line 1 of 10
Line 2 of 10
Line 3 of 10
Line 4 of 10

如果您打印deque d,您可以看到線條的去向:

>>> d
deque(['Line 5 of 10\n', 'Line 6 of 10\n', 'Line 7 of 10\n', 'Line 8 of 10\n', 'Line 9 of 10\n', 'Line 10 of 10\n'], maxlen=7)

使用數組逐個填充所有文本。 然后使用while()或if條件。 這可能對您有所幫助: 用Python讀取和寫入文件

例:

>>> for line in f:
        print line

然后在最后一次迭代發生之前使用中斷。

暫無
暫無

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

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