如何添加一个列表到文件.txt



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

[1, “Amin Milani Fard”, “Columbia College”, 778]
[2, “Ali”, “Douiglas College”, 77238]
def addingcustomer(file_name,new_name):
    f=open(file_name,'w')
    for line in f:
        if new_name==line:
            return ("already existed")
        elif new_name!=line:
            f.write(str(new_name)+"n")
            return ("succesfully added")

它给了我这个错误:

Traceback (most recent call last):
  File "C:UsersYuvinngDesktopCustomer assignment 1Customer assignment 2", line 77, in <module>
    function(c)
  File "C:UsersYuvinngDesktopCustomer assignment 1Customer assignment 2", line 26, in function
    print (addingcustomer("customerlist.txt",x))
  File "C:UsersYuvinngDesktopCustomer assignment 1Customer assignment 2", line 60, in addingcustomer
    for line in f:
io.UnsupportedOperation: not readable

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

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")

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

下面是可能导致错误的几个因素:

  1. 你开始:"我应该添加一个客户名称到customer.txt文件",但你张贴的堆栈跟踪说,你试图读取的文件是"customerlist.txt"

  2. 您正在使用带有'w'的file_open函数作为写权限。尝试使用'r'或'wr'。

e .

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

我假设代码中的每一行都是一个形式为

的python列表
line = [id, fullname, establishment, some_integer]

,您(或其他人)通过将其写入名为file_name的文件的一行来存储它。这一点都不像蟒蛇。您应该使用像CSV(逗号分隔值)这样的标准格式(python在其带有CSV模块的库中支持该格式)。作为分隔符,您可以选择逗号、分号或任何您想要的东西。假设您选择了分号作为分隔符。那么该文件将看起来像这样:

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文件。然后使用csvreadercsvWriter添加行到你的文件,如果他们不存在。

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

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()

最新更新