Home > Back-end >  Read and write CSV file in Python
Read and write CSV file in Python

Time:12-23

I'm trying to read sentences in a csv file, convert them to lowercase and save in other csv file.

import csv
import pprint

with open('dataset_elec_4000.csv') as f:
    with open('output.csv', 'w') as ff:
        data = f.read()
        data = data.lower
        writer = csv.writer(ff)
        writer.writerow(data)

but I got error "_csv.Error: sequence expected". What should I do? *I'm a beginner. Please be nice to me:)

CodePudding user response:

You need to read over your input CSV row-by-row, and for each row, transform it, then write it out:

import csv

with open('output.csv', 'w', newline='') as f_out:
    writer = csv.writer(f_out)

    with open('dataset_elec_4000.csv', newline='') as f_in:
        reader = csv.reader(f_in)

        # comment these two lines if no input header
        header = next(reader)
        writer.writerow(header)

        for row in reader:
            # row is sequence/list of cells, so...
            # select the cell with your sentence, I'm presuming it's the first cell (row[0])
            data = row[0]

            data = data.lower()
            
            # need to put data back into a "row"
            out_row = [data]

            writer.writerow(out_row)

CodePudding user response:

Python contains a module called csv for the handling of CSV files. The reader class from the module is used for reading data from a CSV file. At first, the CSV file is opened using the open() method in ‘r’ mode(specifies read mode while opening a file) which returns the file object then it is read by using the reader() method of CSV module that returns the reader object that iterates throughout the lines in the specified CSV document.

import csv 
   # opening the CSV file 
with open('Giants.csv', mode ='r')as file: 
   # reading the CSV file 
csvFile = csv.reader(file) 
   # displaying the contents of the CSV file 
for lines in csvFile: 
print(lines) 
  • Related