[英]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.