1

I have written this code

import os
import csv
import time

class upload_CSV:

    def __init__(self):
        coup = []
        self.coup = coup
        self.csv_name = 'Coup.csv'

    def loader(self,rw):
        with open(self.csv_name,'rb') as csv_file:
            reader = csv.reader(csv_file,delimiter=',')
            for row in reader:
                self.coup.append(row[rw])

            self.coup = self.coup[1:]
            csv_file.flush()
            csv_file.close()
        return self.coup

    def update(self,rw,message):
        #try:
        with open(self.csv_name,'rb') as csv_file1:
            reader = csv.reader(csv_file1,delimiter=',')
            csv_file1.flush()#To clean the register for reuse
            csv_file1.close()
        #except Exception as ex:
        #error = 'An error occured loading data in the reader'
        #   #raise
        #   return ex    

        os.remove(self.csv_name)
        writer = csv.writer(open(self.csv_name,'wb'))

        for row in reader:
            if row[rw]==message:
                print str(row),' has been removed'
            else:
                writer.writerow(row)
        return message

I am trying to read the content of a csv to a list first. Once i get the relevant data, i need to go back to my csv and create a new entry without that record. I keep getting the single error

Line 27 in update
with open(csv_name,'rb')as csvfile1:
Python: IOError: [Errno 2] No such file or directory 'Coup.csv' 

when i call the Update function

I have looked at this question Python: IOError: [Errno 2] No such file or directory but nothing seems to work. Its as if the first function has a lock on the file. Any help would be appreciated

Community
  • 1
  • 1
Magondu
  • 197
  • 5
  • 20

1 Answers1

0

It would be enormously helpful if we saw the traceback to know exactly what line is producing the error...but here is a start...

First, you have two spots in your code where you are working with a filename that expects to only be available in the current directory. That is one possible point of failure in your code if you run it outside the directory containing the file:

self.csv_name = 'Coup.csv'
...
with open(self.csv_name,'rb') as csv_file:
...
with open('Coup.csv~','rb') as csv_file1:
...

And then, you are also referring to a variable that won't exist:

def update(self,rw,message):
    ...
    # self.csv_name? or csv_file1?
    os.remove(csv_name)
    writer = csv.writer(open(csv_name,'wb'))

Also, how can you be sure this temp file will exist? Is it guaranteed? I normally wouldn't recommend relying on a system-temporary file.

with open('Coup.csv~','rb') as csv_file1:
jdi
  • 90,542
  • 19
  • 167
  • 203