簡體   English   中英

使用 Python 點擊​​讀取 JSON 文件

[英]Using Python Click to read a JSON file

我是 python 的新手,我正在嘗試讀取一個 JSON 文件,現在我可以直接寫出一個新文件而無需任何更改。 我一直在嘗試使用 python 包 Click 來執行此操作,但一直遇到錯誤。

我相信這是相對基本的,但任何幫助將不勝感激。 我試過的最新版本的代碼如下。

 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實現這一目標:

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