Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

python - csv.writerows() puts newline after each row

This is an example from the O'Reilly Cookbook (truncated dataset)

headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [{'Symbol': 'AA', 'Volume': 181800, 'Change': -0.18,
         'Time': '9:36am', 'Date': '6/11/2007', 'Price': 39.48},
        {'Symbol': 'AIG', 'Volume': 195500, 'Change': -0.15,
         'Time': '9:36am', 'Date': '6/11/2007', 'Price': 71.38} ]

with open('stocks2.csv','w') as f:
    f_csv = csv.DictWriter(f, headers)
    f_csv.writeheader()
    f_csv.writerows(rows)

the output file has a at the end of each line, and apparently one more at the end. When I bring it into Excel, I get blank lines between each row. The same if I open it with Notepad++.

But, if I more if from a command line, the don't show up.

I saw another Q&A about a at the end of a file - but this one is about a at the end of each line. (And I don't see why more doesn't give the .)

I plan to bring the file into OpenOffice Calc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This problem occurs only with Python on Windows.

In Python v3, you need to add newline='' in the open call per:

Python 3.3 CSV.Writer writes extra blank rows

On Python v2, you need to open the file as binary with "b" in your open() call before passing to csv

Changing the line

with open('stocks2.csv','w') as f:

to:

with open('stocks2.csv','wb') as f:

will fix the problem

More info about the issue here:

CSV in Python adding an extra carriage return, on Windows


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...