Skip to content

Instantly share code, notes, and snippets.

@prehensilecode
Created May 15, 2018 20:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prehensilecode/9d0b2f6a1421649ee15f559f5952bdb6 to your computer and use it in GitHub Desktop.
Save prehensilecode/9d0b2f6a1421649ee15f559f5952bdb6 to your computer and use it in GitHub Desktop.
Test pandas.read_csv() with an argparse.FileType() object
#!/usr/bin/env python3
import sys, os
import csv
import pandas as pd
import argparse
def read_csv(csvfile):
print('read_csv(): type(csvfile)) = {}'.format(csvfile))
print('')
foo_df = pd.read_csv(csvfile)
return foo_df
def main():
parser = argparse.ArgumentParser(description='Make barchart from csv.')
parser.add_argument('-d', '--debug', help='Debugging output', action='store_true')
parser.add_argument('csvfile', type=argparse.FileType('r'), help='Input csv file')
args = parser.parse_args()
print('main(): type(args.csvfile)) = {}'.format(args.csvfile))
print('')
### This works
foo_df = pd.read_csv(args.csvfile)
print(foo_df.describe())
print('')
print(foo_df.head(5))
print('')
### This does not work
foo_df = read_csv(args.csvfile)
print(foo_df.describe())
print('')
print(foo_df.head(5))
if __name__ == '__main__':
main()
@dumbledad
Copy link

Why? They look the same to me

@prehensilecode
Copy link
Author

Why? They look the same to me

Did you try it out?

@crawoo
Copy link

crawoo commented Oct 26, 2022

I think I see what you're doing here. How would you go about writing back to the csv file after making some changes to it?

@prehensilecode
Copy link
Author

I think I see what you're doing here. How would you go about writing back to the csv file after making some changes to it?

I wouldn't: I would write to a new file. Then, if I really wanted to, os.replace()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment