0

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.

ZiZ0GaminG
  • 19
  • 1
  • 4

2 Answers2

0

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)
gold_cy
  • 13,648
  • 3
  • 23
  • 45
  • Thanks for the tip, but each number is still in single quotes, and I need 2 numbers between double quotes seperated by comma. – ZiZ0GaminG Jan 04 '22 at 13:12
  • that is what `join` will do, I edited it to include the `,` separator – gold_cy Jan 04 '22 at 13:13
  • I did that also, but I'm still not getting the format I need, and it is also taking all the values for 1st column, then for second, its not taking values per row: ['-73.933087,40.6960679', '-84.39591587,39.34949003', '-111.2325173,47.49438049', '-86.37423545,39.60040222', '-81.73030972,28.54595711', '-94.15517103,30.08338437'] – ZiZ0GaminG Jan 04 '22 at 13:18
  • I managed to do it, I conveted the list to string and then using 'replace' function I removed and changed all characters I needed to match my desired output. – ZiZ0GaminG Jan 04 '22 at 14:21
  • not sure what you are saying but that output looks like what you asked for – gold_cy Jan 04 '22 at 15:16
-1

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.

  • this does not answer the question, please consider reading --> https://stackoverflow.com/help/how-to-answer – gold_cy Jan 04 '22 at 12:24
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 04 '22 at 14:20