Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7.1: How to Open, Edit and Close a CSV file

I'm having trouble opening a file (amount2.csv) making a change, saving it and closing the file.

How does one open a file edit, save and close it?

import csv

changes = {
    '1 dozen' : '12'
    }
with open('amount2.csv', 'r') as f:
reader = csv.reader(f)
print f
f.close()

my error: open file 'amount2.csv', mode 'r' at 0x1004656f0 (<> removed)

like image 733
Sean Avatar asked Jan 23 '13 01:01

Sean


People also ask

How do I edit an existing CSV file in Python?

Editing the contents of an existing CSV file will require the following steps: read in the CSV file data, edit the lists (Update information, append new information, delete information), and then write the new data back to the CSV file.

How do I open and edit a CSV file?

Open the CSV file in Microsoft Excel or a compatible application, such as a text editor or Notepad. Move your cursor to an empty line and type an H in column A. Press the Tab key to move to the next column and enter the value that you want to import for that field. Repeat step b for all the fields in the row.


1 Answers

The

<open file 'amount2.csv', mode 'r' at 0x1004656f0>

you are seeing isn't an error, but the result of your 'print f'. To instead see the contents of your file, you would do

with open('test.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        # row is a list of strings
        # use string.join to put them together
        print ', '.join(row)

To append rows to your file, instead do

changes = [    
    ['1 dozen','12'],                                                            
    ['1 banana','13'],                                                           
    ['1 dollar','elephant','heffalump'],                                         
    ]                                                                            

with open('test.csv', 'ab') as f:                                    
    writer = csv.writer(f)                                                       
    writer.writerows(changes)

More info at Python CSV Docs

EDIT:

I misunderstood at first, you want to change all entries of '1 dozen' to '12' in your csv file. I will say first, this is easier to do without using the csv module, but here is a solution using it.

import csv

new_rows = [] # a holder for our modified rows when we make them
changes = {   # a dictionary of changes to make, find 'key' substitue with 'value'
    '1 dozen' : '12', # I assume both 'key' and 'value' are strings
    }

with open('test.csv', 'rb') as f:
    reader = csv.reader(f) # pass the file to our csv reader
    for row in reader:     # iterate over the rows in the file
        new_row = row      # at first, just copy the row
        for key, value in changes.items(): # iterate over 'changes' dictionary
            new_row = [ x.replace(key, value) for x in new_row ] # make the substitutions
        new_rows.append(new_row) # add the modified rows

with open('test.csv', 'wb') as f:
    # Overwrite the old file with the modified rows
    writer = csv.writer(f)
    writer.writerows(new_rows)

If you're new to programming and python the most trobulesome line is probably

new_row = [ x.replace(key, value) for x in new_row ]

but this is just a list comprehension that is effectively equivalent to

temp = []
for x in new_row:
    temp.append( x.replace(key, value) )
new_row = temp
like image 195
kalhartt Avatar answered Oct 27 '22 00:10

kalhartt