简体   繁体   中英

Python - save csv file with tab separated words in separate cell

I have this input file:

one\tone
two\ttwo
three\tthree

With a tab between each word.

I am trying to save it in a csv file where each word ends up in its own cell. This is my code:

import csv

input = open('input.txt').read()
lines = input.split('\n')

with open('output.csv', 'w') as f:
   writer = csv.writer(f)   
   for line in lines:
     writer.writerow([line])

However, both words end up in the same cell:

在此处输入图片说明

How do I change the code so that each word ends up in its own cell?

Try this:


import csv

input = open('input.txt').read()
lines = input.split('\n')

with open('output.csv', 'w') as f:
   writer = csv.writer(f)   
   for line in lines:
     writer.writerow(line.split('\t'))

You need to split the input lines into a list, so that csv.writer() will put them into seperate columns. Try:

with open('output.csv', 'w') as f:
   writer = csv.writer(f)   
   for line in lines:
       writer.writerow(line.split('\t'))

The writerow method in the CSV writer library takes a list of columns.

Currently, you are providing your whole string the value of the first column

 writer.writerow([line])

Instead, try splitting the string by \\t , thus creating a list of each individual word and provide that to the library instead.

writer.writerow(line.split("\t"))

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