我得到一个类型错误,我的类在其函数dl()中使用self
import urllib
import httplib
import os.path
###SAI22 Library###
def exists(site):
conn = httplib.HTTPConnection(site)
conn.request("HEAD",site)
response = conn.getresponse()
conn.close()
return response.status == 200
class sai_download:
def dl(self,_dir,_url,pck):
if pck == True:
if exists(_url) == True:
urllib.urlretrieve(_url,_dir)
if os.path.isfile(_dir) == True:
print "Download successful"
return True
else:
print "Download failed"
return False
else:
print "Url isnt valid"
return False
elif pck == False:
if exists(_url) == True:
urllib.urlretrieve(_url,_dir)
return True
if os.path.isfile(_dir) == True:
return True
else:
return False
else:
return …Run Code Online (Sandbox Code Playgroud) 我正在帮助某人从网站上提取一堆(数万)pdf文件.我们有文件名的模式,但不是所有文件都存在.我假设要求提供一个不存在的文件是很粗鲁的,特别是在这种规模上.我正在使用python,在我的urllib2测试中,我发现这个片段会在文件存在的情况下获取该文件
s=urllib.urlretrieve('http://website/directory/filename.pdf','c:\\destination.pdf')
Run Code Online (Sandbox Code Playgroud)
如果该文件不存在,那么我将得到一个文件,其中包含我分配的名称,但文件来自404页面.现在我可以在完成后处理这个(读取文件并删除所有404页面),但这对他们的服务器来说似乎不太好,也不是非常pythonic.
我试着看看urllib和urlretrieve中的各种函数,并且没有看到任何告诉我文件是否存在的东西.
请考虑以下代码:
def readPath(path):
content = None
if os.path.isfile(path):
f = open(path,"rb")
content = f.read()
f.close()
return content
Run Code Online (Sandbox Code Playgroud)
与这一个:
def readPath(path):
content = None
try:
f = open(path,"rb")
content = f.read()
f.close()
except:
pass
return content
Run Code Online (Sandbox Code Playgroud)
鉴于def被连续调用多次(数百到数千次),主要是使用有效路径(代表文件系统上的实际文件),但有时使用不存在的路径,哪个版本更有效?在打开文件之前检查条件是否比设置try块慢?
我正在尝试制作一个 python 脚本来在一个每天都有条目的 excel 文件中创建条目。我想检查一个文件是否存在然后打开它。如果文件不存在,那么我想创建一个新文件。
if have used os path exists 查看文件是否存在
workbook_status = os.path.exists("/log/"+workbookname+".xlxs")
if workbook_status = "True":
# i want to open the file
Else:
#i want to create a new file
Run Code Online (Sandbox Code Playgroud)