0

I have a csv file which has a column of dates and I m importing that using the below code.

Problem is when i map that to a list of strings, it is printed as below.

["['05/06/2020']", "['1/6/2020']", "['5/22/2020']"]

With this I'm unable to check if the list contains my value(eg: another date) after doing necessary formatting.

I would like this to be

['05/06/2020', '1/6/2020', '5/22/2020']

with open('holidays.csv','r') as csv_file:
    csv_Reader = csv.reader(csv_file)
    next(csv_Reader)
    listDates = list(map(str,csv_Reader))

    print(listDates)
3
  • What is in the actual file? listDates = list(csv_Reader) would seem to be sufficient. Commented Jun 13, 2020 at 15:33
  • It has a single column of dates. Yes, I tried your line of code before using the map(str,)... But it returned me list of lists which i don't want as I had little difficulty checking whether the date inputted by the user is available in the list. Commented Jun 13, 2020 at 15:40
  • listDates = [x[0] for x in csv_Reader]? Commented Jun 13, 2020 at 16:12

4 Answers 4

3

You can just simply add one extra line like so:

with open('holidays.csv','r') as csv_file:
    csv_Reader = csv.reader(csv_file)
    next(csv_Reader)
    listDates = list(map(str,csv_Reader))
    listDates = [x.split("'")[1] for x in listDates]

    print(listDates)

Hope this helps :)

Sign up to request clarification or add additional context in comments.

Comments

0

Use ast.literal_eval in a list comprehension to evaluate individual elements and capture the first entry:

import ast

lst = ["['05/06/2020']", "['1/6/2020']", "['5/22/2020']"]

res = [ast.literal_eval(x)[0] for x in lst]
# ['05/06/2020', '1/6/2020', '5/22/2020']

Comments

0

Like this:

l = ["['05/06/2020']", "['1/6/2020']", "['5/22/2020']"]
l = [s[2:-2] for s in l]
print(l)

Output:

['05/06/2020', '1/6/2020', '5/22/2020']

Comments

0

If your file looks like this

05/06/2020
01/06/2020
05/22/2020

all you need is

with open('holidays.csv','r') as csv_file:
    csv_Reader = csv.reader(csv_file)
    next(csv_Reader)
    listDates = [row[0] for row in csv_Reader]

Each row will be a list of fields, even if there is only one field.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.