【问题标题】:Saving a file in a directory but also being able to print it whenever i needto将文件保存在目录中,但也可以在需要时打印
【发布时间】:2015-04-07 15:20:52
【问题描述】:

我正在运行 Python 3.x。所以我一直在研究一些代码,用于从货币网站获取世界各地货币名称的数据,以获取代码如下的信息

def _fetch_currencies():
    import urllib.request
    import json
    f = urllib.request.urlopen('http://openexchangerates.org/api/currencies.json')
    charset = f.info().get_param('charset', 'utf8')
    data = f.read()
    decoded = json.loads(data.decode(charset))
    dumps = json.dumps(decoded, indent=4)
    return dumps

然后我需要将其保存为本地文件,但有一些问题并且看不到位置。

这是保存货币的代码:

def save_currencies(_fetch_currencies, filename):   
    sorted_currencies = sorted(decoded.items())
    with open(filename, 'w') as my_csv:
       csv_writer = csv.writer(my_csv, delimiter=',')
       csv_writer.writerows(sorted_currencies)

除了我删除“dumps = json.dumps(decoded, indent=4)”行之外,它们似乎不能一起工作,但我需要该行才能以文本形式打印文件,怎么办我绕过删除这一行,仍然能够保存和打印?我该如何选择它的保存位置?

任何帮助都会很棒,非常感谢回答/阅读此内容的任何人和每个人。

【问题讨论】:

    标签: python csv python-3.x save


    【解决方案1】:

    我可能弄错了,但是您的“解码”变量应该在两个函数中声明为全局变量。

    【讨论】:

      【解决方案2】:

      我实际上会让 _fetch_currencies() 返回一个字典,然后我会将该字典传递给 saved_currencies(currencies_decoded, 文件名)。例如:

      def _fetch_currencies():
          import urllib.request
          import json
          f = urllib.request.urlopen('http://openexchangerates.org/api/currencies.json')
          charset = f.info().get_param('charset', 'utf8')
          data = f.read()
          decoded = json.loads(data.decode(charset))
          return decoded
      
      def save_currencies(currencies_decoded, filename):   
          sorted_currencies = sorted(currencies_decoded.items())
          with open(filename, 'w') as my_csv:
             csv_writer = csv.writer(my_csv, delimiter=',')
             csv_writer.writerows(sorted_currencies)
      
      my_currencies_decoded = _fetch_currencies()
      save_currencies(my_currencies_decoded, "filename.csv")
      

      此外,如果您想将 csv 文件保存到文件系统中的某个位置,您可以导入 os 并使用 os.path.join() 函数并为其提供完整路径。例如,要将 .csv 文件保存到名为“/Documents/Location/Here”的位置,您可以:

      import os
      
      def save_currencies(currencies_decoded, filename):   
          sorted_currencies = sorted(currencies_decoded.items())
          with open(os.path.join("Documents","Location","Here"), 'w') as my_csv:
             csv_writer = csv.writer(my_csv, delimiter=',')
             csv_writer.writerows(sorted_currencies)
      

      您也可以使用相对路径,这样如果您已经在“Documents”目录中,并且想将文件保存在“/Documents/Location/Here”中,您可以直接说:

      with open(os.path.join("Location", "Here"), 'w') as my_csv:
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-10
        • 1970-01-01
        • 2019-08-02
        • 2020-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多