读取csv时格式不正确

时间:2018-08-15 05:52:04

标签: python-3.x csv

CSV格式(3列):

id_numb formatted_id    Comment_Txt
    1    Z007         sample text says good morning.

要读取的代码:

with open("file.csv", 'r' ,newline='') as csvfile:
   file_reader = csv.reader(csvfile, delimiter=' ',quotechar='|')

   for row in file_reader:  
       print(row)

预期的操作次数:

['id_numb', 'formatted_id', 'Comment_Txt']
['1',  'Z007', 'sample','text' ,'says','good','morning.']

我的OP:

['1,Z007,sample',   'text' ,'says','good','morning.']

前三个令牌会自动加入。我无法理解错误。任何建议都将有所帮助。

2 个答案:

答案 0 :(得分:1)

import csv
from functools import reduce

with open("file.csv", 'r' ,newline='') as csvfile:
    file_reader = csv.reader(csvfile, delimiter=',',quotechar='|')

    for row in file_reader:
        print(reduce(lambda x, y: x+y, [i.split(' ') for i in row]))

输出:

['id_numb', 'formatted_id', 'Comment_Txt']
['1', 'Z007', 'sample', 'text', 'says', 'good', 'morning.']

Expected OP吗?

答案 1 :(得分:0)

您可以尝试使用

react-native init --version="0.54.0" ProjectName

因为您的第一行似乎是表格

with open("file.csv", 'r' ,newline='') as csvfile:
   file_reader = csv.reader(csvfile, delimiter=',',quotechar='|')

   for row in file_reader:  
       print(row)

并使用''作为分隔符基本上将由空格分隔的所有内容分成两个不同的列。