【问题标题】:Allow User to Name New File [closed]允许用户命名新文件[关闭]
【发布时间】:2016-06-14 00:50:32
【问题描述】:

如何让用户自己命名“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')

【问题讨论】:

  • 这段代码没有告诉我们任何事情......

标签: python


【解决方案1】:

从 arg 解析 file_name,然后使用类似:

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

【讨论】:

  • 这不是pythonic,更不用说你假设每个文件都以.ecg结尾
  • 为什么这不是pythonic??我以为他想用与原始后缀相同的后缀来存储这个文件
  • pythonic 方式是使用with,因为它会为您打开和关闭文件,而且可读性更强。也是不好的假设,因为 OP 说他想要任何名字。
  • @Seekheart 对不起? with 声明可能会使事情变得更容易,但是当您拥有大量文件和东西时,情况并非如此。与with 语句相比,这种方式并不多或少。这是完全合理的。奇怪的是,你自己的答案并不符合你自己的期望。
【解决方案2】:

所有你需要做的就是在线

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

替换为

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 2016-12-17
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    相关资源
    最近更新 更多