Problem Treating .csv File Datas In Python
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 forma
Solution 1:
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.
Demo
$ 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
>>> withopen('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')]
Solution 2:
Seems to me that you misunderstood the .csv file index. A row in your file looks like this:
('15', '10', '11', '17');
But I think a row should look like this, what could explain what python did weird things:
15, 10, 11, 17
Sincerly, Chris Fowl.
Solution 3:
- The
delimiter
parameter refers to the delimiter for each field, not each line. So the delimiter here is,
not;
. - Your file is not a well-formatted csv, so if I knew the structure of the file and had to create a csv, this is what I would do:
with open('logsTESTII.csv') as f, open('out.csv', 'w') as of:
for line in f:
line = line.replace(";", "").replace(")", "").replace("(", "")
of.write(line)
Post a Comment for "Problem Treating .csv File Datas In Python"