【问题标题】:How to save a csv file to a certain folder on computer?如何将csv文件保存到计算机上的某个文件夹?
【发布时间】:2015-06-22 08:42:34
【问题描述】:

我不明白程序的 dest_url=r'goog.csv' 部分。我认为它是用来将我们从互联网上获得的文件保存到计算机的,但是当没有保存功能时,计算机如何理解它必须保存文件。就好像我们只有一个 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)

【问题讨论】:

    标签: python csv


    【解决方案1】:

    请注意,下一行打开文件进行写入。

    fx = open(dest_url, "w")
    

    "w" 表示 写入 模式。 接下来的 2 行使用此 fx 对象通过 stream 写入文件。

    最后fx.close() 刷新缓冲区(即写入文件中剩下的任何内容),然后关闭流并保存文件。

    【讨论】:

    • 不过,我仍然感到困惑。 “打开”函数中的第一个参数不是文件名吗?计算机如何知道我们是否真的保存了文件?
    • 确实,第一个参数是文件名。 dest_url 有文件名,不是吗?
    • 问题在于教程中的那个人说我们将从 Internet 下载的任何内容保存到一个名为 goog.csv 的文件中。这是一个正确的说法吗?
    • 是的,好像是这样。代码发送请求,逐行读取响应并将其写入文件。
    【解决方案2】:

    起初这让我很困惑。当脚本运行时,文件名保存在与脚本相同的 Python 文件夹中,因此 Bucky 只需获取文件名并将其传递给变量 (dest_url)。因为文件名位于同一个脚本文件夹中,所以计算机自动知道“Goog.csv”。

    【讨论】:

      【解决方案3】:

      如果您使用数据框或任何其他文件类型,pandas 库可能是您的最佳选择

      将 pandas 导入为 pan

      所以在这种情况下,如果我们有一个数据框...

      file = pan.DataFrame("数据框的路径或数据框的内容") file.to_csv("example.csv 或保存 csv 的路径")

      【讨论】:

        【解决方案4】:

        解释如下:

        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. 
        

        【讨论】:

          猜你喜欢
          • 2015-01-07
          • 1970-01-01
          • 2020-07-13
          • 1970-01-01
          • 1970-01-01
          • 2013-06-13
          • 2021-09-10
          • 1970-01-01
          • 2015-10-05
          相关资源
          最近更新 更多