Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need to rewrite a csv to a new file. In the new file the delta will be calculated and put into a column as well as the direction the delta moves

I’m trying to modify a csv but keep getting the error:

 modifiedFile.write(new)
ValueError: I/O operation on closed file.

The code I did is:

originalFileName = 'C:/Users/Janedoe/Desktop/My Projects/tickerinfo.csv'
modifiedFileName = 'C:/Users/Janedoe/Desktop/My Projects/tickerInfoWithDelta.csv'

def calculateDelta(o, c):
    oInt = float(closingPrice)
    cInt = float(openingPrice)
    calculatedDelta = (oInt-cInt)
    return calculatedDelta

def direction():
    if calculatedDelta > 0 :
        direction = 1
    else:
        direction = 0
    return direction

with open(originalFileName, 'r', encoding = 'utf8') as originalFile, open(modifiedFileName, 'w', encoding = 'utf8') as modifiedFile:
    header = 'Date,Close,Open,Delta,Direction'
    line = originalFile.readline()
    line = originalFile.readline()
while line != '':
    lineList = line.split(',')
    date = lineList[1]
    closingPrice = lineList[2]
    openingPrice = lineList[5]
    delta = calculateDelta(openingPrice, closingPrice)
    new = str(date) + ',' + str(closingPrice) + ',' + str(openingPrice) + ',' + str(delta) + ',' + str(direction) + '\n'
    modifiedFile.write(new)

When I open the modified file, it is blank. It’s for a beginner’s python course, so that being said my knowledge is limited and anything helps!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

modifiedFile is "opened" on the with open line. After that indentation context ends, the file is closed.

You can’t write to a closed file.

One thing you can do is move the writes under that with open context (indentation).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading