【问题标题】:Using Python Click to read a JSON file使用 Python 点击​​读取 JSON 文件
【发布时间】:2021-10-16 20:14:32
【问题描述】:

我是 python 新手,我正在尝试读取一个 JSON 文件,现在我可以直接写入一个新文件而不做任何更改。我一直在尝试使用 python 包单击执行此操作,但一直遇到错误。

我确信这是相对基本的,但我们将不胜感激。我试过的最新版本的代码如下。

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

【问题讨论】:

  • click 与这些有什么关系? Jusa 接受文件名作为第一个命令行参数。您正在尝试使用文字名称 path 而不是该名称的变量中的字符串打开一个文件。
  • 我最终要加载和输出 5 个文件,因此使用 click 可以让我添加更多功能并看起来更美观。抱歉,如果这个问题看起来很愚蠢,这是针对大学的,我对此比较陌生。

标签: python command-line-interface


【解决方案1】:

这样的事情可以让您了解如何使用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()

【讨论】:

  • 哇,非常感谢。
  • @DanS 不客气
猜你喜欢
  • 1970-01-01
  • 2016-12-03
  • 2018-11-02
  • 1970-01-01
  • 2017-04-21
  • 2021-06-01
  • 2019-02-25
  • 2017-10-03
相关资源
最近更新 更多