我正在嘗試讀取 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:預期序列”。我該怎么辦?*我是初學者。請對我好點:)
uj5u.com熱心網友回復:
您需要逐行閱讀輸入的 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)
uj5u.com熱心網友回復:
Python 包含一個名為 csv 的模塊,用于處理 CSV 檔案。模塊中的 reader 類用于從 CSV 檔案中讀取資料。首先,在 'r' 模式下使用 open() 方法打開 CSV 檔案(在打開檔案時指定讀取模式),它回傳檔案物件,然后使用 CSV 模塊的 reader() 方法讀取它,該方法回傳遍歷指定 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/391111.html
上一篇:從while回圈匯出到csv檔案
