gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:49:40 25 4
gpt4 key购买 nike

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

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

最佳答案

您的代码可以简化:

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)

关于Python-将列表添加到文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29270098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com