[Tutor] awk like functionality in python

Alan Gauld alan.gauld at yahoo.co.uk
Wed Sep 14 13:15:24 EDT 2016


On 14/09/16 11:02, Alan Gauld via Tutor wrote:

> - fileinput lets you process all files in a sub-directory tree.

Duh, no it doesn't. It  processes all the files in a list
of filenames. Apologies. Correct usage is demonstrated below...


> But using fileinput makes it slightly simpler,
> the whole thing then reduces to:
> 
> import fileinput as fin
> FILE_DIR = "/home/ronw/my_python_journey/names"
> data = {}
> for line in fin.input(os.listdir(FILE_DIR))
>     births = int(line.split()[2])
>     # year = line.split[???] # is there a year field
>     data.setdefault(fin.filename(),0) += births # or use year as key?
> 
> print(data)
> 
> Which basically processes every file in the directory
> line by line. It extracts the birth figure and converts
> it to an integer. It then inserts/adds it into a
> dictionary(data) based on the filename. At the end
> it prints the dictionary

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list