简体   繁体   English

使用 Python argparse,如果未指定我的输出文件的名称,我希望使用输入文件的名称

[英]Using Python argparse, if the name of my output file is not specified, I would like the input file’s name to be used

All of the examples use sys.stdout as the default for an optional output file.所有示例都使用sys.stdout作为可选输出文件的默认值。 I would like the default to use the name of my input but with the extension changed.我希望默认使用我的输入名称,但扩展名已更改。 For example, if my input file is example.gif then I would like the default output file to be named example.png .例如,如果我的输入文件是example.gif那么我希望将默认输出文件命名为example.png I am trying to write a subclass of argparse.FileType to do this, but would appreciate it if someone has previously solved this problem.我正在尝试编写argparse.FileType的子类来执行此操作,但如果有人以前解决了此问题,我将不胜感激。

Please directly look at @alkasm comment.请直接看@alkasm 评论。 It's far better and shorter!!它更好更短!!

I use something similar to name my default log files.我使用类似的东西来命名我的默认日志文件。 Could you try this?你能试试这个吗?

def change_file_ext(file_path, new_ext='.out'):
    from pathlib import Path
    in_file_path = Path(file_path)
    out_file_path = Path(Path(in_file_path.parent), Path(in_file_path.stem + new_ext))
    return out_file_path

Note that both in_file_path, out_file_path are instances of pathlib.PosixPath .请注意, in_file_path, out_file_path都是pathlib.PosixPath实例。 That should be cross platform那应该是跨平台的

For ex:例如:

print(change_file_ext('/some/dir/filename.in'))
print(change_file_ext('C:\\some\\dir\\filename.in', new_ext='.log'))

Will yeld:会喊:

/some/dir/filename.out
C:\some\dir\filename.log

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

相关问题 我想让我的python将输出写入到csv文件吗? - I would like my python to write my output to a csv file? 使用 python3,我想获取特定日期范围内所有文件的文件名、文件大小和文件创建日期 - Using python3, I would like to get file name, file size, and file creation date for all files within a specific date range 如何从Python argparse将参数名称写入文件? - How can I write the argument name from Python argparse to a file? Python-命名输出文件以包含部分输入文件名 - Python - name output file to include part of input file name Python argparse输入文件错误 - Python argparse input file error 如何从输入目录文件夹输入并以与输入文件相同的名称将输出文件保存在python中的输出文件夹中 - How to input from input direcory folder and save output file in same name as input file in output folder in python 使用argparse创建输出文件 - Using argparse to create output file 我想将来自 PySimpleGUI 的用户输入用于我的输出 Excel 文件名之一 - I want to use User input from PySimpleGUI to one of my output Excel file name python: matplotlib output 文件名 - python: matplotlib output file name 我如何使用argparse制作一个Python3文件来读取文件内容? - How would I make a Python3 file with argparse that would read the contents of a file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM