What I'm trying to do:
I'm trying to change the formatting on a csv file from space delimited to comma delimited.
What I've done:
I can ingest the csv file just fine, and print the output row-by-row to the console. That code looks like this:
with open(txtpath, mode='r', newline='') as f:
fReader = csv.reader(f)
for rows in fReader:
print(rows)
This does exactly what it's supposed to, and spot checking the output confirms that the rows are being read correctly.
The Problem:
According to the official Python3 Documentation on csv.writer, "If csvfile is a file object, it should be opened with newline='' 1." My code looks like this:
with open(csvpath, 'w') as g:
gWriter = csv.writer(g, newline='')
gWriter.writerows(rows)
so all together, it looks like this:
with open(txtpath, mode='r', newline='') as f:
fReader = csv.reader(f)
for rows in fReader:
print(rows)
with open(csvpath, 'w') as g:
gWriter = csv.writer(g, newline='')
gWriter.writerows(rows)
However, when I run the code with both Pycharm (Anacondas 3.4 selected as project interpreter) and from the console with python3 mycode.py, both results tell me that newline "is an invalid keyword argument for this function" and references line 42, which is where my writer object is instantiated. I ran it through the debugger and it craps out as soon as I try to create the writer object. If I don't add the newline argument it asks for a dialect specification, so that doesn't work, either.
I'm sure there's something blindingly obvious that I'm missing, but I can't see it.
解决方案
The wording is just a bit vague. The file should be opened with newline='', but newline is not a valid option for csv.writer() itself.