简体   繁体   English

Python-使用制表符分隔的单词将csv文件保存在单独的单元格中

[英]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. 我试图将其保存在一个csv文件中,其中每个单词都以其自己的单元格结尾。 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. 您需要将输入行拆分为一个列表,以便csv.writer()将其放入单独的列中。 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. CSV writerow 库中writerow方法采用列列表。

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. 而是尝试用\\t分割字符串,从而创建每个单词的列表,并将其提供给库。

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

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

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