I719 Fundamentals of Python/lecture3
From ICO wiki
Lecture 3
Lets review! - lists - dictionaries - strings - comparison operators
Command line arguments
The standard library has sys
which give us access to the command line arguments executed.
import sys
if '-h' in sys.argv or '--help' in sys.argv:
print('Sorry I can\'t help you :(')
But argparse
from the standard library is much easier if we want to use the commandline arguments.
File opening
f = open(filename)
# interact with the file
f.close()
# is the same as
with open(filename) as f:
# interact with the file
here is an example of a script that opens a file, and print all lines in the file. The file name is specified as the first command line argument
"""
Print all lines in file
"""
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('file_name')
args = parser.parse_args()
text_file = open(args.file_name)
for line in text_file:
cleaned_line = line.strip() # Remove newline, i.e. '\n' or '\r\n'
print(cleaned_line)
text_file.close()
if __name__ == '__main__':
main()
TASK 1
Print out a dictionary with words and the number of occurences of the word.
Example output:
{'Apple': 10, 'Bananan': 1}
How to count words in a list of words
>>> words = ['hello', 'hi', 'hello']
>>> wc = {}
>>> for word in words:
... if word in wc:
... wc[word] = wc[word] + 1
... else:
... wc[word] = 1
...
...
...
>>> wc
{'hello': 2, 'hi': 1}
>>>
Task 2
Make a new csv file and save it, where the age become year born.
Solution
"""
convert input csv to output csv
"""
import argparse
import csv
def convert_age_in_csv(data_in, data_out):
reader = csv.reader(data_in)
writer = csv.writer(data_out)
for row in reader:
name = row[0].strip()
age = int(row[1])
year_born = 2017 - age
writer.writerow([name, year_born])
def main():
parser = argparse.ArgumentParser()
parser.add_argument('data_in')
parser.add_argument('data_out')
args = parser.parse_args()
with open(args.data_in, 'r') as data_in:
with open(args.data_out, 'w') as data_out:
convert_age_in_csv(data_in, data_out)
if __name__ == '__main__':
main()
How to execute
python3 csvconverter.py input.csv output.csv