我不了解该计划的 dest_url = r' goog.csv' 部分。我认为它用于保存从Internet到计算机的文件,但是当没有保存功能时,计算机如何理解它必须保存文件。就好像我们只有一个dest_url变量并为其分配一个字符串值。
from urllib import request
goog_url = 'http://real-chart.finance.yahoo.com/table.csv?s=GOOG&d=8&e=2&f=2014&g=d&a=2&b=27&c=2014&ignore=.csv'
def download_stock_data(csv_url):
response = request.urlopen(csv_url)
csv = response.read()
csv_str = str(csv)
lines = csv_str.split("\\n")
dest_url = r'goog.csv'
fx = open(dest_url, "w")
for line in lines:
fx.write(line + "\n")
fx.close()
download_stock_data(goog_url)
答案 0 :(得分:0)
请注意,下一行将打开文件进行编写。
fx = open(dest_url, "w")
"w"
表示写入模式。
接下来的两行使用此fx
对象使用流写入文件。
最后fx.close()
刷新缓冲区(即写入留给文件的任何内容),然后关闭流并保存文件。
答案 1 :(得分:0)
起初这对我来说非常困惑。运行脚本时,文件名保存在与脚本相同的Python文件夹中,因此Bucky只需获取文件名并将其传递给变量(dest_url)。由于文件名位于同一脚本文件夹中,因此计算机会自动识别“Goog.csv”。
答案 2 :(得分:0)
如果你正在使用数据框或任何其他文件类型,pandas库可能是你最好的选择
将pandas导入为pan
所以在这种情况下,如果我们有数据帧......
file = pan.DataFrame(“数据帧的路径或数据帧的内容”) file.to_csv(“example.csv或保存csv的路径”)
答案 3 :(得分:0)
以下是说明:
dest_url = r'goog.csv' # this line will only hold the name of future file, dont think like this variable will create a file"
fx = open(dest_url, "w") # Here open() method will bring you a blank csv file with file name as det_url in which we have already assigned some value to it. and 'w' will allow the file to be writable.
for line in lines: # In order to load goog.csv file with the date we have already captured in lines variable, we need to user for loop, as this is a easy way to feed the empty file of any type.
fx.write(line + "\n") # Here write() will fetch each of the strings present inside lines variable and writes on goog.csv file as you already know. once the for loop exits, it will save automatically the contents present inside it.
fx.close() # This is exit the file after saving the changes.