Completed
Push — master ( 87fb07...159278 )
by Jerome
01:13
created

persist()   B

Complexity

Conditions 6

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
dl 0
loc 12
rs 8
1
from sys import version_info
2
if version_info[0] == 2:
3
    from itertools import izip_longest as zip_longest
4
elif version_info[0] == 3:
5
    from itertools import zip_longest
6
from itertools import (takewhile,repeat)
7
import os
8
9
def obtain(filename):
10
    with open(filename, 'r') as file:
11
        categories = []
12
        res = []
13
        for i, line in enumerate(file):
14
            if i == 0:
15
                categories = list(map(str.strip,line.strip().split("\t")))
16
            else:
17
                res.append(dict(zip_longest(categories, map(str.strip,line.split("\t")),fillvalue="")))
18
    return res
19
20
def persist(filename,dict,mode="a",split="\t"):
21
    order = None
22
    if filename in os.listdir(os.getcwd()):
23
        with open(filename) as file:
24
            order = file.readline().strip().split(split)
25
    with open(filename,mode) as file:
26
        if order is None:
27
            order = list(dict.keys())
28
            file.write(split.join(order))
29
            file.write("\n")
30
        file.write(split.join([str(dict[i]) for i in order]))
31
        file.write("\n")
32
33
34
def count(filename):
35
    """Credits to Michael Bacon/Quentin Pradet from Stackoverflow
36
37
    filename -- Name of the file, of which the amount of lines shall be counted
38
    """
39
    f = open(filename, 'rb')
40
    bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
41
    return sum(buf.count(b'\n') for buf in bufgen)
42