如何修改csv.writer代码实现无空白的垂直CSV输出?
Got it, let's sort out that blank line problem and get your timeSeries values stacked cleanly one per line in the CSV file.
Why the Blank Lines Happen
Your original code has two potential culprits:
- On Windows systems, the default
open()function andcsv.writerboth handle line endings, causing duplicate newlines that show up as blank rows. - Using
csv.QUOTE_ALLwraps every value in quotes, which might not be necessary if you just want plain values separated by newlines.
Solution 1: Simplest Approach (No CSV Module Needed)
If your timeSeries elements are simple (no commas, quotes, or special characters), you can skip the csv module entirely and write directly to the file. This gives you full control over the output:
with open('timeSeries.csv', 'w') as myfile: for value in timeSeries: myfile.write(f"{value}\n")
This will write each value on its own line, no extra blank rows, no quotes—exactly like your example (3, 5, 6 each on separate lines).
Solution 2: Using CSV Module (For Special Characters)
If you need to handle values with commas or special characters (and still want no blank lines), adjust the csv.writer parameters to fix line endings and control quoting:
Option A: No Quotes, Clean Lines
import csv # Use newline='' to let csv module handle line endings correctly with open('timeSeries.csv', 'w', newline='') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_NONE, escapechar='') # Write each value as a single-element row wr.writerows((value,) for value in timeSeries)
Option B: Keep Quotes (If Needed)
If you still want every value wrapped in quotes but no blank lines:
import csv with open('timeSeries.csv', 'w', newline='') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerows((value,) for value in timeSeries)
Key Takeaway
- Use Solution 1 for straightforward, plain-value outputs—it's faster and simpler.
- Use Solution 2 only if you need CSV-specific handling (like escaping special characters).
内容的提问来源于stack exchange,提问作者Hammerstein

