简体   繁体   中英

Writing List to CSV in Python

I'm writing data from a PDF to a CSV. The CSV needs to have one column, with each word on a separate row.

The code below writes each word on a separate row, but also puts each letter in a separate cell.

with open('annualreport.csv', 'w', encoding='utf-8') as f:
    write = csv.writer(f)
    for i in keywords:
        write.writerow(i)

I have also attempted the following, which writes all the words to one row, with each word in a separate column:

with open('annualreport.csv', 'w', encoding='utf-8') as f:
    write = csv.writer(f)
    write.writerow(keywords)

As far as I know, writerow expects an array. Thus a word is treated as an array with the individual letters -> each letter is written into a new cell.

Putting the value into a single array should fix the problem:

with open('annualreport.csv', 'w', encoding='utf-8') as f:
    write = csv.writer(f)
    for i in keywords:
        write.writerow( [ i ] ) # <-- before: write.writerow(i)
import csv 

# data to be written row-wise in csv fil 
data = [['test'], [try], ['goal']] 
# opening the csv file in 'w+' mode 
file = open('output.csv', 'w+', newline ='') 

# writing the data into the file 
with file:     
    write = csv.writer(file) 
    write.writerows(data) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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