2015-11-23 42 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