IMP  2.1.0
The Integrative Modeling Platform
csv_related.py
1 """@namespace IMP.em2d.csv_related
2  Utility functions to handle CSV files.
3 """
4 
5 import csv
6 
7 def is_comment(list_values, comment_char = "#"):
8  if(len(list_values) == 0 or list_values[0][0] == comment_char):
9  return True
10  return False
11 
12 def read_csv(fn, delimiter = "|", comment_char = "#", max_number=False):
13  """
14  Simple reader of csv files that disregards lines with comments
15  """
16  f = open(fn, "r")
17  reader = csv.reader(f, delimiter=delimiter)
18  if(max_number):
19  i = 1
20  rows = []
21  for r in reader:
22  if(i>max_number):
23  break
24  rows.append(r)
25  i+=1
26  else:
27  rows = [d for d in reader if(not is_comment(d, comment_char))]
28  f.close()
29  return rows
30 
31 
32 def read_csv_keyword(fn_or_f,keyword, delimiter = "|",
33  comment_char = "#"):
34  """
35  Reader of csv files that only recovers lines starting with a keyword
36 
37  """
38  if(type(fn_or_f) == str):
39  f = open(fn_or_f, "r")
40  elif(type(fn_or_f) == file):
41  f = fn_or_f
42 
43  reader = csv.reader(f, delimiter=delimiter)
44  rows = []
45  for row in reader:
46  if(not is_comment(row) and row[0] == keyword):
47  rows.append(row)
48 
49 
50  if(type(fn_or_f) == str):
51  f.close()
52 
53  return rows