【问题标题】:How to write a file to a specified folder如何将文件写入指定文件夹
【发布时间】:2019-11-26 05:55:09
【问题描述】:

我正在处理 .json 到 .csv 的转换。我正在从文件夹中读取 .json 文件并将其拆分,然后将结果写入同一文件夹中。

我想要的是将这些结果文件写入不同的文件夹。

    new_path = 'C:/Users/toc/Desktop/Python_Codes/Data/Input'
    name = askopenfilename(initialdir="C:/Users/toc/Desktop/Python_Codes/Data/JSON_File",
                           filetypes=(("Json File", "*.json"), ("All Files", "*.*")),
                           title="Choose a file."
                           )
    try:
        with open(name,'r', encoding='utf8') as infile:
            o = json.load(infile)
            chunkSize = 1
        for i in range(0, len(o), chunkSize):
            with open(name + '_' + str(i//chunkSize) + '.json', 'w') as outfile:
                json.dump(o[i:i+chunkSize], outfile)
    finally:
        print("No file exists")

上面的代码是工作文件,我唯一需要知道的是如何将这些多个.json文件写入另一个文件夹,即new_path

【问题讨论】:

    标签: python python-3.x file path


    【解决方案1】:

    可以使用os.chdir()函数改变当前目录:https://docs.python.org/3.5/library/os.html#os.chdir

        import os
        new_path = 'C:/Users/toc/Desktop/Python_Codes/Data/Input'
        name = askopenfilename(initialdir="C:/Users/toc/Desktop/Python_Codes/Data/JSON_File",
                               filetypes=(("Json File", "*.json"), ("All Files", "*.*")),
                               title="Choose a file."
                               )
        try:
            with open(name,'r', encoding='utf8') as infile:
                o = json.load(infile)
                chunkSize = 1
            os.chdir(newpath)
            new_name = os.path.basename(name)
            for i in range(0, len(o), chunkSize):
                with open(new_name + '_' + str(i//chunkSize) + '.json', 'w') as outfile:
                    json.dump(o[i:i+chunkSize], outfile)
        finally:
            print("No file exists")
    

    编辑:正如 ShadowRanger 所说,您需要先使用 os.path.basenamename 中删除目录。

    【讨论】:

    • name 很可能是一个合格的路径,所以os.chdir 不会改变你写输出的位置,除非你从中剥离目录组件(例如使用os.path.basename )。
    【解决方案2】:

    这是一种相对常见的操作,您可以通过谷歌搜索找到很多方法,但要回答您的问题...

    您可以将任何合格的文件传递给打开,因此我们只需要将您的新路径与文件结合起来(正如@Tajinder 在他的回答中所做的那样)。您可以查看库以帮助使其更安全、更清洁,但我喜欢使用 os.path

    所以你的代码可能看起来像这样:

        import os
        new_path = 'C:/Users/toc/Desktop/Python_Codes/Data/Input'
        name = askopenfilename(initialdir="C:/Users/toc/Desktop/Python_Codes/Data/JSON_File",
                               filetypes=(("Json File", "*.json"), ("All Files", "*.*")),
                               title="Choose a file."
                               )
        try:
            with open(name,'r', encoding='utf8') as infile:
                o = json.load(infile)
                chunkSize = 1
            for i in range(0, len(o), chunkSize):
                with open(os.path.join(newpath, os.path.basename(name).rsplit('.',1)[0] + '_' + str(i//chunkSize) + '.json'), 'w') as outfile:
                    json.dump(o[i:i+chunkSize], outfile)
        finally:
            print("No file exists")
    

    已编辑以进行快速修复(阅读不是最干净的方式)以从名称中删除目录部分和扩展名,@ShadowRanger 正确指出这很可能是一个合格的路径。

    【讨论】:

      【解决方案3】:

      希望,我正确理解了您的问题。您可以检查以下代码。 我认为你可以在写作时用文件名提及路径。将C:/Path_to_output_directory/ 更改为实际输出路径。

      变化: with open( 'C:/Path_to_output_directory/' + name + '_' + str(i // chunkSize) + '.json', 'w') as outfile:

      new_path = 'C:/Users/toc/Desktop/Python_Codes/Data/Input'
      name = askopenfilename(initialdir="C:/Users/toc/Desktop/Python_Codes/Data/JSON_File",
                             filetypes=(("Json File", "*.json"), ("All Files", "*.*")),
                             title="Choose a file."
                             )
      try:
          with open(name, 'r', encoding='utf8') as infile:
              o = json.load(infile)
              chunkSize = 1
          for i in range(0, len(o), chunkSize):
              with open(  'C:/Path_to_output_directory/' +  os.path.basename(name) + '_' + str(i // chunkSize) + '.json', 'w') as outfile:
                  json.dump(o[i:i + chunkSize], outfile)
      finally:
          print("No file exists")
      

      【讨论】:

      • name 将是一个合格的路径。在为输出文件创建名称时,您很可能希望在其上使用 os.path.basename
      • @ShadowRanger,是的,你是对的。感谢提及。
      猜你喜欢
      • 1970-01-01
      • 2013-08-22
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 2012-10-31
      相关资源
      最近更新 更多