html_str
リストではなく文字列です。
次のようなことができます。
txt='''\
Line 1
line 2
line 3
line 4
last line'''
print txt.rpartition('\n')[0]
または
print txt.rsplit('\n',1)[0]
rpartitionとrsplitの違いは、ドキュメントで確認できます。ターゲット文字列に分割文字が見つからない場合に何をしたいかによって、どちらかを選択します。
ところで、次の方法でファイルを開いて書き込むことができます。
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)