简体   繁体   中英

Why am I getting “_csv.Error: newline inside string”?

There is one answer to this question:

Getting "newline inside string" while reading the csv file in Python?

But this didn't work when I used the accepted answer.

If the answer in the above link doesn't work and you have opened multiple files during the execution of your code, go back and make sure you have closed all your previous files when you were done with them.

I had a script that opened and processed multiple files. Then at the very end, it kept throwing a _csv.Error in the same manner that Amit Pal saw.

My code runs about 500 lines and has three stages where it processes multiple files in succession. Here's the section of code that gave the error. As you can see, the code is plain vanilla:

f = open('file.csv')
fread = csv.reader(f)
for row in fread:
    do something

And the error was:

for row in fread:

_csv.Error: newline inside string

So I told the script to print what the row....OK, that's not clear, here's what I did:

print row
f = open('file.csv')
fread = csv.reader(f)
for row in fread:
    do something

Interestingly, what printed was the LAST LINE from one of the previous files I had opened and processed.
What made this really weird was that I used different variable names, but apparently the data was stuck in a buffer or memory somewhere.

So I went back and made sure I closed all previously opened files and that solved my problem.

Hope this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM