Home > Software design >  Read CSV file in custom string format
Read CSV file in custom string format

Time:01-05

I have a .csv file which looks something like this:

-73.933087,40.6960679
-84.39591587,39.34949003
-111.2325173,47.49438049

How can I read that .csv file in python to get format like this(2 numbers between quotes seperated by comma):

numbers = ["-73.933087,40.6960679",
           "-84.39591587,39.34949003",
           "-111.2325173,47.49438049"]

I managed to load .csv in list, but I formatting is the problem.

import csv
with open('coordinates.csv', newline='') as f:
    reader = csv.reader(f)
    my_list = list(reader)

print(my_list)

input("Press enter to exit.")

Where I get output like this:

[['-73.933087', '40.6960679'], 
['-84.39591587', '39.34949003'], 
['-111.2325173', '47.49438049']]

So I need to remove single quotes here, and to change square brackets for double quotes.

CodePudding user response:

Just use join to combine each line. You were 95% there with your code already.

import csv

numbers = []

with open('coordinates.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        nums = ",".join(row)
        numbers.append(nums)

CodePudding user response:

I think you should simply be able to store it in a pandas dataframe like this:

import pandas as pd

numbers = pd.read_csv (r'Path where the CSV file is stored\File name.csv')
print (numbers)

Then you can convert it to a numpy array or whatever you like.

  •  Tags:  
  • Related