Python-将列表添加到文件末尾

时间:2015-03-26 02:31:08

标签: python list file

我正在尝试创建将文件变量和客户记录(作为列表)作为参数的函数,并将该客户信息添加到文件的末尾。例如:

> f = open( "customers.txt", "a+", encoding="utf-8" )
> data = ['2134', 'Lee', 'Stan', 287.56, '2008-10-10']
> append_customer( f, data )

现在这是我目前的代码:

add_record=input("Enter the record you want to enter: ")


l = open(r'C:\Users\John\Downloads\Eclipse\customers.txt','a', encoding="utf-8")

contents= l.readlines()

def get_new_customer(contents, add_record):
    new_record=[]
    for new_record in add_record:
        new_record+= add_record
        contents.write(new_record)

l.close()

get_new_customer(contents,add_record)

然而,我收到错误:

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\John\\Downloads\\Eclipseee\\customers.txt'

由于此错误,我甚至不确定无论ERRNO 13权限错误,我的代码是否都能正常工作。

如果有人有任何建议/意见,请指教! 〜GIO〜

1 个答案:

答案 0 :(得分:1)

您的代码可以简化:

def get_new_customer(fh, add_record):  
    # join record data into a string  
    new_line = ",".join(add_record)
    # write it to the last line of the file
    fh.write(new_line + "\n")


# Customer data separted by comma
add_record=input("Enter the record you want to enter: ")

# get costumer data as list by spliting on coma
data = add_record.split(',')

# open the file and add the customer data to it.
with open(r'/tmp/customers.txt','a+', encoding="utf-8") as l:
    get_new_customer(l, data)