我正在尝试从一个网站读取一个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'
...
我想把文件放在电脑上,但同时要保持格式。
您应该使用readlines()读取整行:
但是,我强烈建议您使用
requests
库。 链接到这里http://docs.python-requests.org/en/latest/如果您只是想将远程文件作为python脚本的一部分保存到本地服务器,那么可以使用PycURL库下载并保存它,而不必解析它。更多信息-http://pycurl.sourceforge.net
或者,如果你想读然后写输出,我想你只是把方法弄乱了顺序。请尝试以下操作:
如果两者都不适用,请更新问题以澄清。
这是因为你在一个字符串上迭代。这将导致字符对字符的打印。
为什么不立即保存整个文件?
如果您真的想在文件行上进行循环,请使用
txt = webf.readlines()
并对其进行迭代。相关问题 更多 >
编程相关推荐