python3函数读取文件写入文件默认覆盖文件
我想创建一个函数,读入一个txt文件,删除每行的前导空格和尾随空格,然后写入一个文件,默认覆盖我读入的文件,但可以选择写入一个新文件。 这是我的密码python3函数读取文件写入文件默认覆盖文件,python,python-3.x,function,input,output,Python,Python 3.x,Function,Input,Output,我想创建一个函数,读入一个txt文件,删除每行的前导空格和尾随空格,然后写入一个文件,默认覆盖我读入的文件,但可以选择写入一个新文件。 这是我的密码 def cleanfile(inputfile, outputfile = inputfile): file1 = open(inputfile,'r') file2 = open(outputfile, 'w') lines = list(file1) newlines = map(lambda x: x.stri
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:未定义名称“inputfile”
请问如何解决这个问题并实现我的目标?非常感谢。您不能将outputfile=inputfile设置为默认参数。这是Python的一个限制—“inputfile”在指定默认参数时不作为变量存在 您可以使用sentinel值:
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'
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')
最好只是将arg2默认为None,并检查它,而不是麻烦使用自定义sentinel对象,除非您需要处理用户提供的None与defaultNo不同
None
在调用方级别上可能具有语义意义。(如果不是的话,你使用空值是错误的。)@user234461 sentinel对我来说是新的,但这种方法是有效的。谢谢。在很多情况下(甚至在标准库中),没有一个是完全可以接受的默认值。查看@avigil的代码os.walk
中的上下文是完全不同的:在这里,onerror=None
实际上意味着在发生错误时,不应该发生任何事情,因此任何理智的调用方将动态生成的None
作为onerror
传递,当发现没有采取任何行动时,都不会感到惊讶。相反,当输出文件被计算为None
时,在输入文件上跺脚是不明智的默认行为:当程序员特别选择不包含第二个参数时,内联执行操作是非常明智的,这并不奇怪$人身侮辱