您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中下载之前获取文件的大小

在Python中下载之前获取文件的大小

我转载了您所看到的:

import urllib, os
link = "http://python.org"
print "opening url:", link
site = urllib.urlopen(link)
Meta = site.info()
print "Content-Length:", Meta.getheaders("Content-Length")[0]

f = open("out.txt", "r")
print "File on disk:",len(f.read())
f.close()


f = open("out.txt", "w")
f.write(site.read())
site.close()
f.close()

f = open("out.txt", "r")
print "File on disk after download:",len(f.read())
f.close()

print "os.stat().st_size returns:", os.stat("out.txt").st_size

输出此:

opening url: http://python.org
Content-Length: 16535
File on disk: 16535
File on disk after download: 16535
os.stat().st_size returns: 16861

在这里做错了什么?os.stat()。st_size是否没有返回正确的大小?

编辑:好的,我找出了问题所在:

import urllib, os
link = "http://python.org"
print "opening url:", link
site = urllib.urlopen(link)
Meta = site.info()
print "Content-Length:", Meta.getheaders("Content-Length")[0]

f = open("out.txt", "rb")
print "File on disk:",len(f.read())
f.close()


f = open("out.txt", "wb")
f.write(site.read())
site.close()
f.close()

f = open("out.txt", "rb")
print "File on disk after download:",len(f.read())
f.close()

print "os.stat().st_size returns:", os.stat("out.txt").st_size

输出

$ python test.py
opening url: http://python.org
Content-Length: 16535
File on disk: 16535
File on disk after download: 16535
os.stat().st_size returns: 16535

确保打开两个文件以进行二进制读/写。

// open for binary write
open(filename, "wb")
// open for binary read
open(filename, "rb")
python 2022/1/1 18:39:51 有296人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶