0

我是 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()
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))

然后您可以使用双端队列循环并执行操作:

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

使用数组一个一个地填充所有文本。然后使用 while() 或 if 条件。这可能会对您有所帮助:Reading & Writing files in Python

例子:

>>> for line in f:
        print line

然后在最后一次迭代发生之前使用中断。

于 2013-11-12T05:30:54.927 回答