如何根据从命令行传递的参数打开文件并删除某些字符

How to open a file and remove certain characters based on args passed from command line

所以我有一个函数,它本质上是 运行 并生成报告并用 args.current_date 文件名保存它。我遇到的问题是从正在保存的文件名中删除扩展名 .json,这实际上是不可读的。由于我将 dict 作为参数传递,因此我无法使用 strip() 方法来执行此操作。到目前为止,我的功能如下:

parser = argparse.ArgumentParser()
parser.add_argument("-c", "--current-date", action="store", required=False)
parser.add_argument("-p", "--previous-date", action="store", required=False)
args = parser.parse_args()

def custom_report(file_names, previous_data , current_data):
    reporting = open('reports/' + args.current_date+ "-report.txt", "w")
    reporting.write("This is the comparison report between the directories" " " + args.current_date +
                    " " "and" " " + args.previous_date + "\n\n")
    for item in file_names:
        reporting.write(item + compare(previous_data.get(item), current_data.get(item)) + "\n")
    reporting.close()

已将文件保存为'2019-01-13.json-report.txt'。我希望能够摆脱 '.json' 方面并将其保留为 '2019-01-13-report.txt'

要删除文件扩展名,可以使用os.path.splitext函数:

>>> import os
>>> name = '2019-01-13.json'
>>> os.path.splitext(name)
('2019-01-13', '.json')
>>> os.path.splitext(name)[0]
'2019-01-13'