0
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()
6
  • open seems to be a reserved word in python, You should refrain from using it as variable name. Commented Mar 18, 2018 at 7:16
  • 2
    Don't just describe the exception, copy the whole thing and paste it here. Python shows you where the exception happens, so you don't have to guess. But if you don't let us see that, we do have to guess. Commented Mar 18, 2018 at 7:17
  • @ZdaR If open were a builtin, this wouldn't happen—it would be a SyntaxError. The problem is that open is a perfectly normal identifier, so it is legal to assign to it. Commented Mar 18, 2018 at 7:20
  • As a side note, you usually don't want to open and close a file each time through a loop. Instead, open it before the loop and close it at the end. (If you were doing this temporarily so you can, e.g., less -f the file to see your script working for debugging purposes, you can saveFile.flush() instead.) Also, you probably want to use a with statement, 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? Commented Mar 18, 2018 at 7:23
  • One more thing: You can use for x, eachDate in enumerate(date): instead of manually managing that x counter. Commented Mar 18, 2018 at 7:24

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.