[英]python3 function read a file write a file default overwrite the file
I want to create a function, read in a txt file, remove leading space and trailing space for each line, then write to a file, default to overwrite the file I read in, but with option to write to a new file. 我想创建一个函数,读取txt文件,删除每行的前导空格和尾随空格,然后写入文件,默认情况下会覆盖我读取的文件,但可以选择写入新文件。 Here is my code.
这是我的代码。
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')
But it give me error. 但这给了我错误。 NameError: name 'inputfile' is not defined
NameError:名称“ inputfile”未定义
How to solve this problem and achieve my goal please? 请问如何解决这个问题并实现我的目标? Thank you very much.
非常感谢你。
standard convention in Python is to use None
as a default and check for that. 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')
You can't set outputfile=inputfile as a default parameter. 您不能将outputfile = inputfile设置为默认参数。 This is a limitation of Python - 'inputfile' doesn't exist as a variable when the default parameter is specified.
这是Python的局限性-指定默认参数后,“ inputfile”作为变量不存在。
You could use a sentinel value: 您可以使用哨兵值:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.