我正尝试使用以下代码将网页数据下载到硬盘驱动器上的samplefile.txt中:
import requests
res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
res.raise_for_status()
playFile = open('samplefile.txt', 'wb')
for chunk in res.iter_content(100000):
playFile.write(chunk)
playFile.close()
代码运行没有错误,但samplefile.txt中没有任何变化。我该如何解决? 谢谢
答案 0 :(得分:0)
import requests
res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
res.raise_for_status()
open('samplefile.txt', 'wb').write(res.content)
这是文件samplefile.txt “”“罗密欧与朱丽叶的古腾堡电子书,威廉·莎士比亚(William Shakespeare) .... “”“
答案 1 :(得分:-1)
import wget
from keras.utils.data_utils import get_file
file1 = get_file('pg1112.txt', 'http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
res = open(file1, "r+")
playFile = open('samplefile.txt', 'w')
for chunk in res.readlines():
playFile.write(chunk)
这对我来说很好。
或者简单地,您可以只使用get_file函数,但是文件将保存在其他路径中。 返回值包含完整的文件路径。
from keras.utils.data_utils import get_file
file1 = get_file('samplefile.txt', 'http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
print(file1) # This is the full file path.