簡體   English   中英

python3函數讀取文件寫入文件默認覆蓋文件

[英]python3 function read a file write a file default overwrite the file

我想創建一個函數,讀取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:名稱“ inputfile”未定義

請問如何解決這個問題並實現我的目標? 非常感謝你。

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')

您不能將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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM