enter image description here我正在使用python 2.7 Flask来开发Web应用程序。我正在尝试从特定URL下载文本文件并保存在应用程序中的静态文件夹中。这是我的代码:
from urllib2 import urlopen
uurl = 'http://textfiles.com/100/ad.txt'
def download(t_url):
response = urlopen(t_url)
data = response.read()
txt_str = str(data)
lines = txt_str.split("\\n")
des_url = 'static/forcast.txt'
fx = open(des_url,"w")
for line in lines:
fx.write(line+ "\n")
fx.close()
download(uurl)
现在我运行此操作并获得以下错误:
Traceback (most recent call last):
File "/Users/sanam/PycharmProjects/ff/ff.py", line 17, in <module>
download(uurl)
File "/Users/sanam/PycharmProjects/ff/ff.py", line 12, in download
fx = open(des_url,"w")
IOError: [Errno 2] No such file or directory: '/static/forcast.txt'
答案 0 :(得分:1)
您的代码没有任何问题,因为它将文件下载到您的python脚本的同一目录中。所以指定文件夹的位置。
from urllib2 import urlopen
uurl = 'http://textfiles.com/100/ad.txt'
def download(t_url):
response = urlopen(t_url)
data = response.read()
txt_str = str(data)
lines = txt_str.split("\\n")
des_url = 'folder/forcast.csv'
fx = open(des_url,"w")
for line in lines:
fx.write(line+ "\n")
fx.close()
download(uurl)
答案 1 :(得分:0)
from urllib2 import urlopen
uurl = 'http://textfiles.com/100/ad.txt'
def download(t_url):
response = urlopen(t_url)
data = response.read()
txt_str = str(data)
lines = txt_str.split("\\n")
des_url = 'folder/add.txt'
with open(des_url,"w"):
for line in lines:
fx.write(line+ "\n")
download(uurl)