Python3引用语法需要帮助

2024-04-26 13:04:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想传输一个文件,但不熟悉python脚本。下面的代码不确定我是否可以这样做。在

  if os.path.exists(fileName):
    outputFile = open(fileName, "ab")
  else
    outputFile = open(fileName, "wb")


  with urllib.request.urlopen(url) as response, outputFile as out_file:
             data = response.read()
             out_file.write(data)

这是错误。在

^{2}$

我知道我可以用这种方式写作(有点多余,试图简化)

  if os.path.exists(fileName):
    with urllib.request.urlopen(url) as response, open(fileName, "ab") as out_file:
             data = response.read()
             out_file.write(data)
  else
    with urllib.request.urlopen(url) as response, open(fileName, "wb") as out_file:
             data = response.read()
             out_file.write(data)

有什么建议吗


Tags: urlreaddataresponserequestaswithopen
1条回答
网友
1楼 · 发布于 2024-04-26 13:04:12

埃里克

我想你在这里至少遇到了两个问题。您也可能会遇到一个实际问题,即您试图从中获取数据的web服务器;但是您的代码中有几个问题需要首先解决。在

第一个注意事项:urlib似乎不支持上下文管理。所以我想你会想要这样的东西:

#!//usr/bin/python
import contextlib, urllib

url = 'http://stackoverflow.com/'
outfilename = '/tmp/foo.out'

with contextlib.closing(urllib.urlopen(url)) as response, open(outfilename, 'w') as output_file:
    output_file.write(response.read())

注意with语句必须包含打开资源的调用和别名(as)。我不知道在封闭块中打开它并尝试在with语句行上执行别名操作将如何工作。。。我很确定它不是一个受支持的语法。(如果你想自己阅读这些参考文献:https://docs.python.org/2/reference/compound_stmts.html#the-with-statement)。在

请注意,我正在使用contextlib提供的包装器来实现返回的对象的上下文管理urllib.urlopen()呼叫。在

注意:在Python3中,这将略有不同:

^{pr2}$

看看有没有帮助。用一个已知有效的URL检查该代码;然后看看您是否能够解决阻碍您对目标的HTTP访问的任何问题。在

相关问题 更多 >