Python LMF library
 All Classes Namespaces Files Functions Variables
io.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 """! @package utils
4 """
5 
6 from utils.error_handling import Error
7 
8 ## Define EOL depending on operating system
9 import os
10 if os.name == 'posix':
11  # Unix-style end of line
12  EOL = '\n'
13 else:
14  # Windows-style end of line
15  EOL = '\r\n'
16 
17 # Define encoding
18 ENCODING = 'utf-8'
19 
20 def open_file(filename, mode, encoding=ENCODING):
21  """! @brief Open file in specified mode (automatically decode file in unicode).
22  @param filename Full path to file to open.
23  @param mode Read or write mode.
24  @param encoding Encoding mode. Default value is 'utf-8'.
25  @return File handler.
26  """
27  try:
28  try:
29  return open(filename, mode, encoding=encoding)
30  except TypeError:
31  import codecs
32  return codecs.open(filename, mode, encoding=encoding)
33  except IOError as exception:
34  raise Error("Cannot open file.", exception)
35 
36 def open_read(filename, encoding=None):
37  """! @brief Open file in read mode (automatically decode file in unicode).
38  @param filename Full path to file to open.
39  @param encoding Encoding mode. Default value is None.
40  @return File handler.
41  """
42  if encoding is None:
43  return open_file(filename, 'rb')
44  else:
45  return open_file(filename, 'rb', encoding=encoding)
46 
47 def open_write(filename, encoding=None):
48  """! @brief Open file in write mode (automatically decode file in unicode).
49  @param filename Full path to file to open.
50  @param encoding Encoding mode. Default value is None.
51  @return File handler.
52  """
53  if encoding is None:
54  return open_file(filename, 'wb')
55  else:
56  return open_file(filename, 'wb', encoding=encoding)
def open_read
Open file in read mode (automatically decode file in unicode).
Definition: io.py:36
def open_write
Open file in write mode (automatically decode file in unicode).
Definition: io.py:47
def open_file
Open file in specified mode (automatically decode file in unicode).
Definition: io.py:20