【问题标题】:python read file from a web URLpython从Web URL读取文件
【发布时间】:2015-10-06 13:50:03
【问题描述】:

我目前正在尝试从网站读取 txt 文件。

到目前为止,我的脚本是:

webFile = urllib.urlopen(currURL)

这样,我可以处理文件。但是,当我尝试存储文件(在webFile 中)时,我只得到一个指向套接字的链接。我尝试的另一个解决方案是使用read()

webFile = urllib.urlopen(currURL).read()

但是,这似乎删除了格式(\n\t 等)。

如果我这样打开文件:

 webFile = urllib.urlopen(currURL)

我可以逐行阅读:

for line in webFile:
    print line

这将导致:

"this" 
"is" 
"a"
"textfile"

但我明白了:

't'
'h'
'i'
...

我希望在我的计算机上获取文件,但同时保持格式。

【问题讨论】:

标签: python urllib readfile


【解决方案1】:

你应该使用 readlines() 来读取整行:

response = urllib.urlopen(currURL)
lines = response.readlines()
for line in lines:
    .
    .

但是,我强烈建议您使用requests 库。 链接在这里http://docs.python-requests.org/en/latest/

【讨论】:

    【解决方案2】:

    这是因为你迭代了一个字符串。这将导致字符打印。

    为什么不一次保存整个文件?

    import urllib
    webf = urllib.urlopen('http://stackoverflow.com/questions/32971752/python-read-file-from-web-site-url')
    txt = webf.read()
    
    f = open('destination.txt', 'w+')
    f.write(txt)
    f.close()
    

    如果您真的想循环遍历文件行,请使用 txt = webf.readlines() 并对其进行迭代。

    【讨论】:

    【解决方案3】:

    如果您只是想将远程文件作为 python 脚本的一部分保存到本地服务器,则可以使用 PycURL 库下载并保存它而无需解析它。更多信息在这里 - http://pycurl.sourceforge.net


    或者,如果您想读取然后写入输出,我认为您只是将方法弄乱了。请尝试以下操作:

    # Assign the open file to a variable
    webFile = urllib.urlopen(currURL)
    
    # Read the file contents to a variable
    file_contents = webFile.read()
    print(file_contents)
    
    > This will be the file contents
    
    # Then write to a new local file
    f = open('local file.txt', 'w')
    f.write(file_contents)
    

    如果两者都不适用,请更新问题以澄清。

    【讨论】:

      【解决方案4】:

      您可以直接下载文件并使用您喜欢的名称进行保存。之后,您可以读取该文件,稍后如果您不再需要该文件,您可以将其删除。

      !pip install wget
      
      import wget 
      url = "https://raw.githubusercontent.com/apache/commons-validator/master/src/example/org/apache/commons/validator/example/ValidateExample.java" 
      wget.download(url, 'myFile.java')
      

      【讨论】:

        猜你喜欢
        • 2018-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2013-04-23
        相关资源
        最近更新 更多