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不返回正确的大小?

编辑:

OK,我想出了什么问题:

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")