-2

Kinda new to this, and writing a script that loads in latitudes and longitudes from a CSV file and converts the formatting for another program to read...finally got it all to work.

I was wondering how I might set this up so I could maybe run ./converter.py filename.csv from a command prompt rather then having the filename embedded in the script?

Currently I have this:

csv_file = open('Vicksburg_9mph_dm.csv') #Defines name of file to open
csv_reader = csv.reader(csv_file, delimiter=',') #Opens file as CSV File
martineau
  • 119,623
  • 25
  • 170
  • 301
tarnis
  • 1
  • 3

1 Answers1

0

Since you said you have a working program (albeit hardcoded for filenames), I'll provide a solution:

import sys
import csv

with open(sys.argv[1], 'r', newline='') as f:
    r = csv.reader(f, delimiter=',')
    # do your work you already do

A couple notes:

sys module contains access to pass CLI arguments

sys.argv is a list of argument variables as discussed in the docs.

with open() syntax is referred to as a context manager. In your provided code, you technically never called close() so the file remained open. When you exit the with block, the file with automatically close.

newline='' flag is specific to Python 3, if you do not have that version simply omit it

pstatix
  • 3,611
  • 4
  • 18
  • 40