【问题标题】:python3 function read a file write a file default overwrite the filepython3函数读取文件写入文件默认覆盖文件
【发布时间】:2018-03-07 15:19:01
【问题描述】:

我想创建一个函数,读入一个txt文件,删除每一行的前导空格和尾随空格,然后写入一个文件,默认覆盖我读入的文件,但可以选择写入一个新文件. 这是我的代码。

def cleanfile(inputfile, outputfile = inputfile):
    file1 = open(inputfile,'r')
    file2 = open(outputfile, 'w')
    lines = list(file1)
    newlines = map(lambda x: x.strip(), lines)
    newlines = list(newlines)
    for i in range(len(newlines)):
        file2.write(newlines[i] + '\n')
    file1.close()
    file2.close()    
cleanfile('hw.txt',)
cleanfile('hw.txt','hw_2.txt')

但它给了我错误。 NameError: name 'inputfile' 没有定义

请问如何解决这个问题并实现我的目标?非常感谢。

【问题讨论】:

    标签: python python-3.x function input output


    【解决方案1】:

    Python 中的标准约定是使用 None 作为默认值并检查它。

    def cleanfile(inputfile, outputfile = None):
        if outputfile is None:
            outputfile = inputfile
        file1 = open(inputfile,'r')
        file2 = open(outputfile, 'w')
        lines = list(file1)
        newlines = map(lambda x: x.strip(), lines)
        newlines = list(newlines)
        for i in range(len(newlines)):
            file2.write(newlines[i] + '\n')
        file1.close()
        file2.close()    
    cleanfile('hw.txt',)
    cleanfile('hw.txt','hw_2.txt')
    

    【讨论】:

      【解决方案2】:

      您不能将 outputfile=inputfile 设置为默认参数。这是 Python 的一个限制 - 当指定默认参数时,'inputfile' 不作为变量存在。

      您可以使用标记值:

      sentinel = object()
      def func(argA, argB=sentinel):
          if argB is sentinel:
             argB = argA
          print (argA, argB)
      
      func("bar")           # Prints 'bar bar'
      func("bar", None)     # Prints 'bar None'
      

      【讨论】:

      • 最好将 arg2 默认为 None 并检查它而不是使用自定义哨兵对象,除非您需要处理用户提供的与默认值没有不同
      • 不,不是。 None 可能在调用者级别具有语义意义。 (如果不是,你使用空值是错误的。)
      • @user234461 sentinel 对我来说是新的,但这种方式有效。谢谢。
      • 在很多情况下(甚至在标准库中) None 是完全可以接受的默认值。查看os.walk的代码
      • @avigil os.walk 中的上下文完全不同:onerror = None 真的意味着发生错误时,什么都不应该发生,所以任何理智的调用者将动态生成的None 传递为@ 987654327@ 发现没有采取任何行动不会感到惊讶。相比之下,当输出文件被计算为None 时,在输入文件上踩踏不是明智的默认行为:当程序员明确选择不包含第二个参数时,执行内联操作是很顽皮的 i> 是完全明智的,并不奇怪。 $personal_insult
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2020-03-19
      • 1970-01-01
      • 2017-06-18
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多