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

时间:2011-07-09 23:43:59

标签: python

您好,我想将客户名称添加到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:\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

4 个答案:

答案 0 :(得分:1)

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

f.close()

答案 1 :(得分:0)

您正在使用w打开文件,这意味着您要求只写权限。然后你尝试遍历文件中的所有行,这显然是一个读操作。 IIRC您应该使用r+w+a+打开文件,具体取决于您想要的行为(read here for a description)。此外,正如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"或将新名称写入文件并返回。因此,该循环将始终在第一行之后返回。此外,即使名称已在稍后存在,如果它不在第一行,它将再次写入文件。由于这是作业,我不会给你完整的解决方案,但作为提示你可能想要在你决定做什么之前循环遍历所有的行。

答案 2 :(得分:0)

可能不是您具体问题的直接答案,但它解决了您的问题作为副作用

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

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

并且您(或其他人)只是通过将其写入名称为file_name的文件中的行来存储它。这根本不是pythonic。您应该为文件使用CSV (Comma-Separated-Value)之类的标准格式(python在其图书馆中使用CSV-module支持)。作为分隔符,您可以选择逗号,分号或任何您想要的。我们假设你选择了一个分号作为分隔符。比文件看起来像这样:

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文件。不,你可以按照描述使用csvreaders和writers。

编辑:

以下代码段可能会帮助您理解我的意思。 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()

答案 3 :(得分:0)

以下是可能导致错误的一些事项:

  1. 您开始时:“我想将客户名称添加到 customer.txt 文件”,但您发布的堆栈跟踪表明您尝试阅读的文件是< b> “customerlist.txt”

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

  3. 电子。

相关问题