Home >Backend Development >Python Tutorial >How to Write Data Line by Line to a CSV File?

How to Write Data Line by Line to a CSV File?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-22 14:24:02700browse

How to Write Data Line by Line to a CSV File?

Writing to a CSV File Line by Line

When working with data in a comma-separated format, it can be necessary to save it to a CSV file. To write data line by line to a CSV file, follow these steps:

Use a Text File and Write Line by Line

Use open() to open a text file in write mode ('w') and then iterate over each line in the data. Write each line to the file followed by a newline character ('n') to create a new row in the CSV file.

<code class="python">with open('fileName.csv', 'w') as f:
    for line in s:
        f.write(line)
        f.write('\n')</code>

Write Using the CSV Writer

The Python csv module provides a convenient way to write to CSV files. With a csv.writer object, you can specify the delimiter (e.g., ,) and write rows to the file using the writerow() method.

<code class="python">import csv
with open('csvfile.csv', "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for line in data:
        writer.writerow(line)</code>

Simple File Write

For a simple solution, you can directly open a text file, write the data followed by newline characters, and close the file. Python automatically converts the newline characters to the system's line separator.

<code class="python">f = open('csvfile.csv','w')
f.write('hi there\n')
f.close()</code>

The above is the detailed content of How to Write Data Line by Line to a CSV File?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn