0

私はpythonが初めてです。スクリプトで最後の行以外のすべてを印刷したい。[:-1] を試しましたが、うまくいきません。以下のコードは私の最初のコードの 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()
4

2 に答える 2

4

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)
于 2013-11-12T05:29:36.577 に答える
-2

配列を使用して、すべてのテキストを 1 つずつ入力します。次に、while() または if 条件を使用します。Pythonでのファイルの読み取りと書き込み

例:

>>> for line in f:
        print line

次に、最後の反復が発生する前にブレークを使用します。

于 2013-11-12T05:30:54.927 に答える