V_Stack_2
V_Stack_2

Reputation: 157

How to add a list into a file .txt

hi i was suppose to add a customer name to a customer.txt file

[1, “Anin Fard”, “B College”, 778]
[2, “Ali”, “C 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")

it gives me this error:

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

Upvotes: 0

Views: 6733

Answers (4)

Aufwind
Aufwind

Reputation: 26238

Probably not a direct answer to your specific question, but it solves your problem as a sideeffect.

I assume that every line in your code is a python list of the form

line = [id, fullname, establishment, some_integer]

and you (or someone else) stored it just by writing it to a line into the file with name file_name. That's not pythonic at all. You should use a standard format like CSV (Comma-Separated-Value) for the file (which python supports in its librarys with the CSV-module). As delimitter you can chose a comma, a semi-colon or what ever you want. Let's assume you chose a semi-colon as delimitter. Than the file would look like this:

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

Assuming a list

mylist = ["1"; "Amin Milani Fard"; "Columbia College"; "778"]

you would need a CSV writer two write to this list:

import csv
wFile = open(file_name, 'w')
csvWriter = csv.writer(wFile, delimiter=';')
csvWriter.writerow(mylist) # write list to csv file
rFile.close()

if you want to read the list again you do:

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

I don't this is a big effort for you but I suggest the following, if you want to clean up the files and your code a little bit: Turn the file into a csv file by reading all the lines into a list. turning every list into a valid python list and then write those lists with csvWriter to your file again which will then be a valid csv file. Then use csvreader and csvWriter to add lines to your file if they do not exist.

In your case (assuming the visible formatting is consistent) I would do:

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

You will have a csv file afterwards. No you can use the csvreaders and writers as described.

Edit:

Perhaps the following code snippets helps you to understand what I meant above. csv readers and writers are really not that complicated. See

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

Upvotes: 0

Erez
Erez

Reputation: 156

Here are a couple of things that might have caused the error:

  1. You started by: "i was suppose to add a customer name to a customer.txt file" but the stack trace you posted says that the file you are trying to read is "customerlist.txt".

  2. You are using the file_open function with 'w' for write privilege. try using 'r' or 'wr'.

E.

Upvotes: 0

Grizzly
Grizzly

Reputation: 20191

You are opening the file with w, meaning you ask for write only permissions. Then you try to loop through all lines in the file, which is clearly a read operation. IIRC you should open the file with r+, w+ or a+, depending on what behaviour you want (read here for a description). Furthermore as mentionened by mh512 it is generally a good idea to close your file with f.close() when you're done with it.

However you might also want to rethink your algorithm.

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

For every line it processes, this will either return "already existed" if it equals the new name or write the new name to the file and return. Therefore this loop will always return after the first line. Furthermore even if the name already exists at a later point, if it isn't in the first line, it will be written to the file again. Since this is homework I won't give you the complete solution, but as a hint you might want to loop through all lines, before you decide what to do.

Upvotes: 0

minghan
minghan

Reputation: 1103

You probably want to close the file too, after you are done.

f.close()

Upvotes: 1

Related Questions