简体   繁体   English

使用 Python 点击​​读取 JSON 文件

[英]Using Python Click to read a JSON file

I am new to python and I am trying to read in a JSON file, that for now I can just write out to a new file without any changes.我是 python 的新手,我正在尝试读取一个 JSON 文件,现在我可以直接写出一个新文件而无需任何更改。 I have been attempting to use the python package Click to do this but keep running into errors.我一直在尝试使用 python 包 Click 来执行此操作,但一直遇到错误。

I'm sure this is relatively basic but any help would be appreciated.我相信这是相对基本的,但任何帮助将不胜感激。 The latest version of the code I've tried is below.我试过的最新版本的代码如下。

 import json
 import os
 import click


 def dazprops():
     """Read Daz3D property File"""
     path = click.prompt('Please specify a location for the Daz3D Properties File')
     path = os.path.realpath(path)
     #dir_name = os.path.dirname(path)
     print(path)
     dazpropsf = open('path')
     print(dazpropsf)


 if __name__ == '__main__':
     dazprops()

Something like this could give you an idea how to achieve that using click :这样的事情可以让您了解如何使用click实现这一目标:

import click

def read_file(fin):
    content = None
    with open(fin, "r") as f_in:
        content = f_in.read()
    return content

def write_file(fout, content):
    try:
        print("Writing file...")
        with open(fout, "w") as f_out:
            f_out.write(content)
        print(f"File created: {fout}")
    except IOError as e:
        print(f"Couldn't write a file at {fout}. Error: {e}")

@click.command()
@click.argument('fin', type=click.Path(exists=True))
@click.argument('fout', type=click.Path())
def init(fin, fout):
    """
    FINT is an input filepath
    
    FOUT is an output filepath
    """
    content = read_file(fin)
    if content:
        write_file(fout, content)
                
if __name__ == "__main__":
    init()

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM