我必须读取 50 GB 的文本文件。我必须对该文件进行一些处理。我无法下载文本文件,因为我正在远程服务器上进行处理。是否可以使用 Python 使用 URL 流式传输文件内容并逐行读取它?
最佳答案
其实最简单的方法是:
import urllib2 # the lib that handles the url stuff
data = urllib2.urlopen(target_url) # it's a file like object and works just like a file
for line in data: # files are iterable
print line
您甚至可以将其缩短为
import urllib2
for line in urllib2.urlopen(target_url):
print line
但请记住,在 Python 中,可读性很重要。
但是,这是最简单的方法,但不是安全的方法,因为在大多数情况下进行网络编程时,您不知道是否会考虑预期的数据量。因此,您通常最好读取固定且合理数量的数据,您知道这些数据足以满足您期望的数据,但会防止您的脚本被淹没:
import urllib2
data = urllib2.urlopen(target_url).read(20000) # read only 20 000 chars
data = data.split("\n") # then split it into lines
for line in data:
print line
In python 3 and up use urllib.request instead of urllib2
关于python - 使用python在线阅读大文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43473332/