2015-11-23 41 views
0
def append_customer(file_variable, fields): 
""" 
------------------------------------------------------- 
Appends a customer record to a sequential file. 
------------------------------------------------------- 
Preconditions: 
    file_variable - the file to search (file) 
    fields - data to append to the file (list) 
Postconditions: 
    The data in fields are appended to file_variable. 
------------------------------------------------------- 
""" 
if os.path.exists(file_variable) == True: 
    file = open(file_variable, "w", encoding="utf-8") 
    file.seek(0) 
    print("{0}".format(fields), file=file_variable) 
file.close() 
return 

的已定義這是一個功能我寫的數據添加到文件中,唯一的錯誤在於顯然是「file_variable未定義」 ......即使它清楚地由函數定義。我不知道爲什麼會發生此錯誤。未定義變量的錯誤,雖然它在功能上

+2

這是你的縮進嗎? –

+0

向我們展示您調用該功能的位置。請[mcve]。 – Kevin

回答

0

這似乎更接近你想要什麼:

def append_customer(file_variable, fields): 
    """ 
    ------------------------------------------------------- 
    Appends a customer record to a sequential file. 
    ------------------------------------------------------- 
    Preconditions: 
     file_variable - the file to search (file) 
     fields - data to append to the file (list) 
    Postconditions: 
     The data in fields are appended to file_variable. 
    ------------------------------------------------------- 
    """ 
    if os.path.exists(file_variable): 
     with open(file_variable, "a", encoding="utf-8") as fobj: 
      fobj.write("{0}\n".format(fields)) 

您需要縮進功能體。

如果你想打開一個現有的文件進行追加,你需要使用'a'這意味着「開放的寫作,追加到文件的末尾,如果它存在」。 with語句打開該文件並在離開縮進時關閉它。

+0

是的,這些都是很好的建議,雖然很難說它們中的任何一個是否會解決OP的錯誤信息。因爲不清楚究竟是什麼造成它的原因。 – Kevin