Import data with Linecache

With this post I want to share 2 nice examples how to read data with Python libraries: os and linecache.

First we need some sample data, you copy data from here:

and save it as .csv [comma-separeated]

Linecache module allows us to get any line from a Python source file. During the attempting to optimize internally, using a cache, the common case where many lines are read from a single file.

import linecache

#loading the file into the console
def import_data(csv_file):
    with open(csv_file, "r") as file_reader:
            for lines in file_reader:
                print(lines, end="")

#file line count
def countLines(CSVfile):
    return len(open(CSVfile, 'rU').readlines())

#reading a single line
def readsingleline(CSVfile,rowNr):
    return linecache.getline(CSVfile, rowNr)

#reading a part of the file (line x to y)
def readsample(plikCSV):
    return linecache.getlines(plikCSV)
  1. Read whole data from file
sample_file = r"sample_file.csv"
print(import_data(sample_file))
result

2. other define functions results

headers = readsingleline(sample_file, 1) #headers
line1 = readsingleline(sample_file, 2)
line2 = readsingleline(sample_file, 3)
line3 = readsample(sample_file)[4:7] #part of
list = [line2] #returns the selected row as a list

#results
print(countLines(sample_file))
print(headers)
print(line1)
print(list)
print(line3)

3. Saving to other file.

#saving data to a new csv file
plik = open("sample_file2.csv", "w")
plik.write(str(line3))
plik.close

Lambda

Lambda expressions are derived from lambda calculus. They are used in practice
as one-line, unnamed (anonymous) functions. They are especially relevant in
functional programming context but are universally applicable.

Simple one

#lambda
x1 = lambda x: x * 2
print(x1(4))

x2 = lambda x,y : x / y
print(x2(10,2))

x3 = lambda x,y,z : x*y/z
print(x3(4,2,10))

If statement, sorted

#lambda instead if statement:
CheckValue = lambda x , y : x if x > y else y
print(CheckValue(3,2))
print(CheckValue(-3,0))

#lambda as key
animals = [
( 'moose' , 'male' , 360 ),
( 'deer' , 'male' , 200 ),
( 'dave' , 'female' , 14 ),
]
animals_by_weight = 
sorted (animals, key = lambda animal : animal[ 2 ])
print (animals_by_weight)

In functions

#lambda in functions
def multiply(n):
  return lambda x : x * n

multi2 = multiply(2)
multi3 = multiply(3)

print(multi2(3))
print(multi3(3))

In classes

#lambda in classes
from operator import itemgetter, attrgetter

class Wilds:
    def __init__(self, name, sex, weight):
        self.name = name
        self.sex = sex
        self.weight = weight

    def _repr_(self):
        return repr((self.name, self.sex, self.weight))

anim_objs = [
Wilds( 'moose' , 'male' , 360 ),
Wilds( 'deer' , 'male' , 200 ),
Wilds( 'dave' , 'female' , 14 ),
]
print ( sorted (anim_objs, key = lambda x : x.weight ))
print ( sorted (anim_objs, key =attrgetter( 'weight' )))