问题

我正在从Web服务器下载整个目录.它工作正常,但我无法弄清楚如何在下载之前获取文件大小,以比较它是否在服务器上更新.这可以像我从FTP服务器下载文件一样完成吗?

 import urllib
import re

url = "http://www.someurl.com"

# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()

f = open ("temp.htm", "w")
f.write (html)
f.close()

# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)

for fname in fnames:
    print fname, "..."

    f = urllib.urlopen(url + "/" + fname)

    #### Here I want to check the filesize to download or not #### 
    file = f.read()
    f.close()

    f = open (fname, "w")
    f.write (file)
    f.close()
 

@Jon:感谢您的快速答案.它有效,但Web服务器上的文件大小略低于下载文件的文件大小.

例如:

 Local Size  Server Size
 2.223.533  2.115.516
   664.603    662.121
 

它与CR/LF转换有什么关系?

  最佳答案

我转载了你所看到的:

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

  相同标签的其他问题

pythonurllib