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!
>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).