【问题标题】:determing file object size before using file object在使用文件对象之前确定文件对象的大小
【发布时间】:2011-04-26 22:32:03
【问题描述】:

我试图在使用 BeautifulSoup 解析和操作之前在 python 中确定下载文件的大小。 (我打算很快更新到 ElementTree,但是在短暂使用过它之后,它并没有解决我在这里提出的问题,据我所知)。

import urllib2, BeautifulSoup
query = 'http://myexample.file.com/file.xml'
f = urllib2.urlopen(query)
print len(f.read())
soup = BeautifulSoup.BeautifulStoneSoup(f.read())

这段代码失败了,因为当我第一次在len()read() 文件时,它自然会到达一个EOF,所以当我想用BeautifulSoup 访问它时,文件对象是空的。

我最初的想法是简单地使用 fcopy = f 行复制对象,但这让我了解到我只是在引用底层对象并没有任何收获。

然后我认为fcopy = copy.copy(f) 会创建对象的真实副本,但显然不是因为读取 f 仍会导致 fcopy 成为空文件对象。

我什至读过关于将对象作为参数传递给函数以解决这个问题,并尝试了以下代码

import urllib2, BeautifulSoup
def get_bytes(file):
    return len(file.read())

query = 'http://myexample.file.com/file.xml'
f = urllib2.urlopen(query)
print(get_bytes(f))
soup = BeautifulSoup.BeautifulStoneSoup(f.read())

但我遇到了同样的问题。如何在不有效破坏文件的情况下确定此对象的文件大小?

【问题讨论】:

    标签: python filesize file-copying


    【解决方案1】:

    将文件的内容复制到一个变量中并使用它:

    import urllib2, BeautifulSoup
    
    query = 'http://myexample.file.com/file.xml'
    f = urllib2.urlopen(query)
    content = f.read()
    print len(content)
    soup = BeautifulSoup.BeautifulStoneSoup(content)
    

    【讨论】:

    • 哇!如此明显!谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多