简体   繁体   中英

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. 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

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.

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. This is a limitation of Python - 'inputfile' doesn't exist as a variable when the default parameter is specified.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM