Python 如何将列表添加到文件.txt中

Python 如何将列表添加到文件.txt中,python,Python,嗨,我想在customer.txt文件中添加一个客户名称 [1, “Amin Milani Fard”, “Columbia College”, 778] [2, “Ali”, “Douiglas College”, 77238] 它给了我这个错误: Traceback (most recent call last): File "C:\Users\Yuvinng\Desktop\Customer assignment 1\Customer assignment 2", line 77,

嗨,我想在customer.txt文件中添加一个客户名称

[1, “Amin Milani Fard”, “Columbia College”, 778]
[2, “Ali”, “Douiglas College”, 77238]
它给了我这个错误:

Traceback (most recent call last):
  File "C:\Users\Yuvinng\Desktop\Customer assignment 1\Customer assignment 2", line 77, in <module>
    function(c)
  File "C:\Users\Yuvinng\Desktop\Customer assignment 1\Customer assignment 2", line 26, in function
    print (addingcustomer("customerlist.txt",x))
  File "C:\Users\Yuvinng\Desktop\Customer assignment 1\Customer assignment 2", line 60, in addingcustomer
    for line in f:
io.UnsupportedOperation: not readable
回溯(最近一次呼叫最后一次):
文件“C:\Users\yuving\Desktop\Customer assignment 1\Customer assignment 2”,第77行,在
职能(c)
文件“C:\Users\yuving\Desktop\Customer assignment 1\Customer assignment 2”,第26行,在函数中
打印(添加客户(“customerlist.txt”,x))
文件“C:\Users\yuving\Desktop\Customer assignment 1\Customer assignment 2”,第60行,添加Customer
对于f中的行:
io.UnsupportedOperation:不可读

完成后,您可能也想关闭该文件

f.close()

您正在使用
w
打开文件,这意味着您请求仅写权限。然后尝试循环文件中的所有行,这显然是一个读取操作。IIRC您应该使用
r+
w+
a+
打开文件,这取决于您想要的行为()。此外,正如mh512所提到的,通常最好在使用完文件后使用
f.close()
关闭文件

但是,您可能还需要重新考虑您的算法

for line in f:
   if new_name==line:
      return ("already existed")
   elif new_name!=line:
      f.write(str(new_name)+"\n")
      return ("succesfully added")

对于它处理的每一行,如果它等于新名称,则返回“已存在”,或者将新名称写入文件并返回。因此,此循环将始终在第一行之后返回。此外,即使该名称在以后某一点已经存在,如果它不在第一行中,它也将再次写入文件。由于这是家庭作业,我不会给你完整的解决方案,但作为一个提示,在你决定做什么之前,你可能想循环所有的行。

可能不是对你的具体问题的直接回答,但它解决了你的问题作为一个副作用

我假设代码中的每一行都是表单的python列表

line = [id, fullname, establishment, some_integer]
您(或其他人)只需将其写入名为
file\u name
的文件中的一行即可将其存储。那根本不是蟒蛇。您应该为文件使用类似的标准格式(python在其库中支持这种格式)。作为定界符,您可以选择逗号、分号或任何您想要的。假设您选择了分号作为定界符。文件的外观如下所示:

id; name; establishment; some_other_id
"1"; "Amin Milani Fard"; "Columbia College"; "778"
"2", "Ali"; "Douiglas College"; "77238"
etc.
假设列表

mylist = ["1"; "Amin Milani Fard"; "Columbia College"; "778"]
您需要一个CSV编写器来写入此列表:

import csv
wFile = open(file_name, 'w')
csvWriter = csv.writer(wFile, delimiter=';')
csvWriter.writerow(mylist) # write list to csv file
rFile.close()
如果要再次阅读列表,请执行以下操作:

rFile = open(file_name, 'r')
csvReader = csv.reader(rFile, delimiter=';')
for row in csvReader: # step throug rows. Each row is a list.
    print ','.join(row)
rFile.close()
我不认为这对你来说是一个很大的努力,但是如果你想稍微清理一下文件和代码,我建议如下:通过将所有行读入列表,将文件转换成csv文件。将每个列表转换为有效的python列表,然后使用
csvWriter
将这些列表再次写入您的文件,该文件将成为有效的csv文件。然后使用
csvreader
csvWriter
将不存在的行添加到文件中

在您的情况下(假设可见格式一致),我会:

import csv
old_name = 'customer.txt'
new_name = 'customer.csv'

rFile = open(old_name, 'r')
wfile = open(new_name, w)

csvWriter = csv.writer(wFile, delimiter=';')

for line in rFile:
    line = line.strip()[1:-1] # strip braces "["  and "]" and newline "\n"
    mylist = line.split(', ') # split the line by ', '
    csvWriter.writerwo(mylist)

rFile.close()
wFile.close()
之后您将拥有一个csv文件。不,您可以使用如上所述的CSVReader和writer

编辑: 也许下面的代码片段可以帮助您理解我上面的意思。csv阅读器和编写器实际上并没有那么复杂。看

import csv

# Creating a customer file with some entrys to start with.
wFile = open('test.csv', 'w') # 'w' means crete fresh file
csvWriter = csv.writer(wFile, quoting=csv.QUOTE_MINIMAL)
csvWriter.writerow(['1', 'old', '2', 'customer'])
csvWriter.writerow(['1', 'an other old', '2', 'customer'])
wFile.close() # Don't forget to close the file

new_customers = [ # List of new customers to add if not exist.
                 ['1', 'old', '2', 'customer'], # will not be added.
                 ['4', 'new', '2', 'customer'] # will be added.
                 ]

# First we wont to eliminate existent customers from list `new_customers`
rFile = open('test.csv', 'r') # 'r' means read file
csvReader = csv.reader(rFile)
print new_customers
for row in csvReader:
    print row
    if row in new_customers:
        new_customers.remove(row) # remove customer if exists
rFile.close() # Don't forget to close the file

if new_customers: # there are new customers left in new_customers
    wFile = open('test.csv', 'a') # 'a' means append to existing file
    csvWriter = csv.writer(wFile, quoting=csv.QUOTE_MINIMAL)
    for customer in new_customers:
        csvWriter.writerow(customer) # add them to the file.
wFile.close()

以下是可能导致错误的两个原因:

  • 您的开头是:“我本来想在customer.txt文件中添加一个客户名称”,但您发布的堆栈跟踪显示您试图读取的文件是“customerlist.txt”

  • 您正在使用“w”表示写入权限的file_open函数。尝试使用“r”或“wr”


  • E.

    如何将代码缩进四个空格以获得正确的格式?sry。。我不知道编辑使用thx来处理向文件写入和读取相同格式的列表。CSV是一种标准。不要重新发明轮子。:-)请看下面我的答案以了解描述。我认为我不允许在我的水平上使用这个。。。因为我以前从没学过。。。无论如何,谢谢。。我现在最大的问题是创建一个while循环,让函数多次读取.txt文件,以确保不存在任何客户,只需将客户及其信息添加到.txt文件即可解决我的问题。。我不知道如何使用while循环进行I/O。。请给我一个开头好吗?def addingcustomer(file_name,new_name):f=open(file_name,“r+”),用于f中的行:而new_name在line:return(“true”)中,而new_name不在line:return(“False”)#这是为了尝试是否读取所有文件)您可能想看看,我想您可能会感兴趣。:-)
    import csv
    
    # Creating a customer file with some entrys to start with.
    wFile = open('test.csv', 'w') # 'w' means crete fresh file
    csvWriter = csv.writer(wFile, quoting=csv.QUOTE_MINIMAL)
    csvWriter.writerow(['1', 'old', '2', 'customer'])
    csvWriter.writerow(['1', 'an other old', '2', 'customer'])
    wFile.close() # Don't forget to close the file
    
    new_customers = [ # List of new customers to add if not exist.
                     ['1', 'old', '2', 'customer'], # will not be added.
                     ['4', 'new', '2', 'customer'] # will be added.
                     ]
    
    # First we wont to eliminate existent customers from list `new_customers`
    rFile = open('test.csv', 'r') # 'r' means read file
    csvReader = csv.reader(rFile)
    print new_customers
    for row in csvReader:
        print row
        if row in new_customers:
            new_customers.remove(row) # remove customer if exists
    rFile.close() # Don't forget to close the file
    
    if new_customers: # there are new customers left in new_customers
        wFile = open('test.csv', 'a') # 'a' means append to existing file
        csvWriter = csv.writer(wFile, quoting=csv.QUOTE_MINIMAL)
        for customer in new_customers:
            csvWriter.writerow(customer) # add them to the file.
    wFile.close()