繁体   English   中英

读写Python中的CSV文件

[英]Read and write CSV file in Python

我正在尝试读取 csv 文件中的句子,将它们转换为小写并保存在其他 csv 文件中。

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)

但我收到错误“_csv.Error:预期序列”。 我应该怎么办? *我是初学者。 请对我好一点:)

Python 包含一个名为 csv 的模块,用于处理 CSV 文件。 模块中的阅读器 class 用于从 CSV 文件中读取数据。 首先,CSV 文件在 'r' 模式下使用 open() 方法打开(指定打开文件时的读取模式)返回文件 object 然后使用 ZCC8D68C551C4A9A6D5313E 模块的 reader() 方法读取它阅读器 object 遍历指定 CSV 文档中的所有行。

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) 

您需要逐行读取您的输入 CSV ,并对每一行进行转换,然后将其写出:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM