Python 允许用户命名新文件

Python 允许用户命名新文件,python,Python,如何允许用户自己命名“copied_holter.ecg”?我提供了这个名称,但我希望用户选择他们想要的任何东西 class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) parser = MyParser(util_help) parser.add

如何允许用户自己命名“copied_holter.ecg”?我提供了这个名称,但我希望用户选择他们想要的任何东西

class MyParser(argparse.ArgumentParser):
def error(self, message):
    sys.stderr.write('error: %s\n' % message)
    self.print_help()
    sys.exit(2)



parser = MyParser(util_help)
parser.add_argument('filename', help='The full path/to/holter_file that you would like to parse.', action="store")
parser.add_argument('packet_start', help='The offset location of the start packet ID in base 10 decimal', action="store", type = int)
parser.add_argument('packet_end', help='The offset location of the end packet ID in base 10 decimal', action = "store", type = int)
parser.add_argument('new_filename', help='The name of the new file with the copied holter data chosen by user.', action = "store")
args = parser.parse_args()

start = args.packet_start
end = args.packet_end

if start % 5 != 0:
  start = int(5*round(float(start)/5))
if end % 5 != 0:
  end = int(5*round(float(end)/5))

try:
  print("Beginning copying of holter data...")

# Output the specific holter data
output_file = open(new_filename+".ecg", 'w')

从arg解析
文件名
,然后使用类似以下内容:

output_file = open(file_name+".ecg", "w")

你所需要做的就是上网

output_file = open(file_name+".ecg", "w")
换成

output_file = open(args.new_filename, 'w')

这段代码没有告诉我们任何事情……这不是pythonic,更不用说你假设每个文件都以
结尾。ecg
为什么这不是pythonic??我想他想用与原始后缀相同的后缀来存储此文件。python的方法是使用
来存储此文件,因为它将为您打开和关闭文件,而且可读性更高。这也是一个错误的假设,因为OP说他想要任何东西作为他的名字。@Seekheart,对不起?
with
语句可能会让事情变得更简单,但当你有大量的文件和东西时,情况就不是这样了。这种方式与
with
语句相比,既不多也不少pythonic。这是完全合理的。奇怪的是,你自己的答案没有达到你自己的期望。