在Python中处理.csv文件数据时遇到问题 [英] Problem treating .csv file datas in Python

查看:93
本文介绍了在Python中处理.csv文件数据时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Ubuntu 18.04下使用Python 2.7,并且正在处理.csv文件中的某些数据.为了在我的脚本中传递它们,我需要将它们以特定格式显示在列表中.它应该是这样的:

I am working with Python 2.7 under Ubuntu 18.04 and I am treating some datas from a .csv file. In order to pass them in my script, I need to have them in a list in a specific format. Here is what it should look like:

data = [('15', '10', '11', '17'),
        ('18', '18', '17', '18'),
        ('12', '17', '17', '18'),
        ('14', '12', '17', '14'),
        ('15', '11', '19', '17')]

.csv文件中包含的每个值"都是一系列用()包围的数字,例如('15','10','11','17')".

each "value" contained in the .csv file is a serie of numbers surrounded by () like that "('15', '10', '11', '17')".

我的.csv文件如下所示:

my .csv file looks like that:

('15', '10', '11', '17');
('18', '18', '17', '18');
('12', '17', '17', '18');
('14', '12', '17', '14');
('15', '11', '19', '17')

和读取csv文件的脚本就是这个:

and the script reading the csv file is this one :

import csv

data = []

with open('logsTESTII.csv', 'r') as f:
    reader = csv.reader(f, delimiter = ';')
    for row in reader:
        data.append(list(reader))

print (data)

无论我做什么,我都尝试了此脚本或.csv文件结构的多种变体,总是得到类似这样的奇怪结果:

no matter what I do, I tried many variation of this script or .csv file structure, I always get weird results like that:

[[["('18', '18', '17', '18')", ''], ["('12', '17', '17', '18')", ''], ["('14', '12', '17', '14')", ''], ["('15', '11', '19', '17')"], [], []]]

我只需要一个包含我所有数据的列表,一个接一个的用逗号分隔.

I just need a list with all my datas , one after the other separated by a comma.

我该如何进行?拜托,这让我发疯了.

How could I proceed ? Please, this is driving me insane.

预先感谢Pixelle

Thanks in advance, Pixelle

推荐答案

您的文件包含元组字面量,实际上不是格式正确的csv数据.
ast.literal_eval csv此处的模块.

Your file consists of tuple-literals, it's not really well-formatted csv data.
ast.literal_eval will serve you better than the csv module here.

演示

$ cat logsTESTII.csv 
('15', '10', '11', '17')
('18', '18', '17', '18')
('12', '17', '17', '18')
('14', '12', '17', '14')
('15', '11', '19', '17')
$ python2.7
>>> from ast import literal_eval
>>> with open('logsTESTII.csv') as f:
...     data = [literal_eval(line) for line in f]
... 
>>> data
[('15', '10', '11', '17'),
 ('18', '18', '17', '18'),
 ('12', '17', '17', '18'),
 ('14', '12', '17', '14'),
 ('15', '11', '19', '17')]

这篇关于在Python中处理.csv文件数据时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆