简体   繁体   English

如何将文件写入指定的文件夹

[英]How to write a file to a specified folder

I'm working on .json to .csv conversion. 我正在将.json转换为.csv。 I am reading a .json file from a folder and splitting the same, and writing the result in the same folder. 我正在从文件夹中读取.json文件并将其拆分,然后将结果写入同一文件夹中。

What I want is to write those resultant files into a different folder. 我想要的是将这些结果文件写入另一个文件夹。

    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")

The above code is working file, the only thing I need to know is how do I write those multiple .json files to another folder, which is new_path 上面的代码是工作文件,我唯一需要知道的是如何将多个new_path文件写入另一个文件夹,即new_path

You can use the os.chdir() function to change the current directory: https://docs.python.org/3.5/library/os.html#os.chdir 您可以使用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")

edit: as ShadowRanger says, you need before to use os.path.basename to remove the directory from name . 编辑:正如ShadowRanger所说,您需要先使用os.path.basenamename删除目录。

Hoping, I understood your question correctly. 希望我能正确理解您的问题。 You can check below code. 您可以检查以下代码。 I think you can mention path also with file name while writing. 我认为您在编写时也可以使用文件名来提及路径。 Chane C:/Path_to_output_directory/ to actual output path. C:/Path_to_output_directory/更改为实际输出路径。

Changes: with open( 'C:/Path_to_output_directory/' + name + '_' + str(i // chunkSize) + '.json', 'w') as outfile: 更改: 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")

This is a relatively common manipulation and you can find a lot of ways to do this with a little googling, but to answer your question... 这是一种相对常见的操作,您可以通过一些谷歌搜索找到很多方法来做到这一点,但是可以回答您的问题...

you can pass any qualified file into open so we only need to combine your newpath with a file (as @Tajinder has done in his answer). 您可以将任何合格的文件传递为打开状态,因此我们只需要将newpath与文件组合(就像@Tajinder在他的回答中所做的那样)。 You can look into libraries to help make this safer and cleaner but I like to use os.path 您可以研究库来帮助使它更安全,更清洁,但是我喜欢使用os.path

so your code might look something like this: 因此您的代码可能看起来像这样:

    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")

Edited to do a quick fix (read not the cleanest way) to remove the directory portion and extension from name which @ShadowRanger rightly pointed out is likely to be a qualified path all on its own. 编辑它是为了快速解决问题(不是最干净的方法),以从@ShadowRanger正确指出的名称中删除目录部分和扩展名,这可能本身就是一个限定路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python Selenium with Chrome,如何下载到指定文件名的指定文件夹 - Python Selenium with Chrome, how to download to a specified folder with specified file name 如何确定指定的文件是否放置在指定的文件夹内? - How to determine whether specified file is placed inside of the specified folder? 如何写入具有指定格式python的文本文件 - How to write into a text file with specified formatting python 如何在Python中创建文件并将指定数量的随机整数写入文件 - How to create a file and write a specified amount of random integers to the file in Python 如何将csv文件写入特定的文件夹 - how to write csv file into specific folder 随机指定文件夹中的文件名 - Randomize file names in a specified folder 如何从现有的 dataframe 将指定的列和行写入 excel 文件? - How to write specified columns and rows to excel file from an existing dataframe? 如何编写脚本来编辑文件夹中的每个Excel文件 - How to write script that edits every excel file inside a folder 如何使用 Python 在 google colab 的特定文件夹中写入文件? - How to write a file on a particular folder on google colab using Python? 如何写入不同文件夹中的文件? (Python) - How do I write to a file that is in a different folder? (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM