python从web URL读取文件

2024-09-27 20:16:30 发布

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

我正在尝试从一个网站读取一个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'
...

我想把文件放在电脑上,但同时要保持格式。


Tags: 文件intxtforread网站链接line
3条回答

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

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

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

如果您只是想将远程文件作为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)

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

这是因为你在一个字符串上迭代。这将导致字符对字符的打印。

为什么不立即保存整个文件?

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()并对其进行迭代。

相关问题 更多 >

    热门问题