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