import numpy as np
def main():
try:
date, price, open = np.loadtxt('CARG.csv', delimiter=',',
unpack=True, dtype='str')
x = 0
for eachDate in date:
saveLine = eachDate + ',' + price[x] + '\n'
saveFile = open('newCSV', 'a')
saveFile.write(saveLine)
saveFile.close()
x += 1
except Exception as e:
print(e)
main()
2 Answers
The problem is that you've named a local variable open, which shadows the builtin function of the same name—but then tried to use the builtin a couple lines later:
date, price, open = …
saveFile = open('newCSV', 'a')
So, instead of calling the builtin, you're calling the array. Which obviously doesn't work.
The solution is just to give your variable a different name.
Comments
I had the same error and it helped me:
import io
with io.open('filename') as f:
#"Doing something you want to do with file"
1 Comment
Community
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
openseems to be a reserved word in python, You should refrain from using it as variable name.openwere a builtin, this wouldn't happen—it would be a SyntaxError. The problem is thatopenis a perfectly normal identifier, so it is legal to assign to it.less -fthe file to see your script working for debugging purposes, you cansaveFile.flush()instead.) Also, you probably want to use awithstatement, so the file gets closed even if there's an exception. Meanwhile, is there a reason you're creating the CSV manually with string concatenation instead of using numpy to do it?for x, eachDate in enumerate(date):instead of manually managing thatxcounter.