我转载了您所看到的:
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")