Skip to content

File Input Output

File i/o

Often times, you will have data stored as an external file. You will need to take this file as input and use it in your code. In this example, we will be using the sys library to take a file as input from the command line. We will iterate over each line of the file and perform a search on the lines.

To begin, we create a file: ‘lookup.csv’

%%file lookup.csv
Date,Time
May,4.15
April,16.00

Code:

%%file io.py
#!/usr/bin/python
import sys
import re
with open(sys.argv[1], 'r') as file:
    for line in file:
        line = re.search(r'May,.*', line) # Regex
        print(line)

Running the Code:

!python io.py lookup.csv

Breakdown:

  • The sys library is used to accept arguments from the command line
  • The re library is used to look for regular expressions within the file
  • with open(sys[1],'r') as file: allows argument 1 from the command line to be opened as stored in the variable file
  • for line in file: Using a for loop, each line of the file is iterated over
  • A search is done on each line for May,.* and matches are printed