Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
reading a line of a CSV
#1
my .csv file could have numbers or quoted strings between the commas. this seems to be the same syntax as that found in a Python literal for a list. so what if i read in a line, .strip() it, prepend '[' to the front, append ']' to the end, and run that through exec() and verify that what is returned is a single simple list with just numbers and strings in it?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
I would definitely use csv module, but if you insist on your approach, at least use ast.literal_eval()
>>>import ast
>>> line = '[1, "some text, with comma", "1,000.5"]'
>>> ast.literal_eval(line)
[1, 'some text, with comma', '1,000.5']
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
it looks like ast.literal_eval() is the way to go.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reading and storing a line of output from pexpect child eagerissac 1 4,148 Feb-20-2024, 05:51 AM
Last Post: ayoshittu
  Reading in of line not working? garynewport 2 786 Sep-19-2023, 02:22 PM
Last Post: snippsat
  [Solved] Reading every nth line into a column from txt file Laplace12 7 5,144 Jun-29-2021, 09:17 AM
Last Post: Laplace12
  Ignore first few letters of a line when reading file. ShakeyPakey 16 6,188 May-30-2020, 02:17 PM
Last Post: BitPythoner
  some help with reading line from CMD on PI korenron 4 2,210 May-21-2020, 08:25 AM
Last Post: korenron
  EOFError: EOF when reading a line - Runtime Error RavCOder 6 9,557 Sep-27-2019, 12:22 PM
Last Post: RavCOder
  reading data from command line mcmxl22 2 1,956 Feb-17-2019, 09:01 PM
Last Post: Axel_Erfurt
  First line of File gets deleted when reading file lrxM 2 4,275 Dec-24-2016, 10:56 AM
Last Post: lrxM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020