def __init__(self, name, mode="rb", buffering=0, temporary=False): """file(name[, mode[, buffering]]) -> file object Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. The preferred way to open a file is with the builtin open() function. Add a 'U' to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a '\n' in Python. Also, a file so opened gains the attribute 'newlines'; the value for this attribute is one of None (no newline read yet), '\r', '\n', '\r\n' or a tuple containing all the newline types seen. 'U' cannot be combined with 'w' or '+' mode. :param temporary: if True, destroy file at close. """ if six.PY2: FileIO.__init__(self, name, mode, buffering) else: # for python3 we drop buffering FileIO.__init__(self, name, mode) self.lock = _Semaphore() self.__size = None self.__temporary = temporary
def __init__(self, fname, mode='rb', endian='<', header_prec='i', *args, **kwargs): """Open a Fortran unformatted file for writing. Parameters ---------- endian : character, optional Specify the endian-ness of the file. Possible values are '>', '<', '@' and '='. See the documentation of Python's struct module for their meanings. The deafult is '>' (native byte order) header_prec : character, optional Specify the precision used for the record headers. Possible values are 'h', 'i', 'l' and 'q' with their meanings from Python's struct module. The default is 'i' (the system's default integer). """ m = mode file.__init__(self, fname, mode=m, *args, **kwargs) self.ENDIAN = endian self.HEADER_PREC = header_prec
def __init__(self, inheritable=False, nonblocking=False): """File-like object wrapping ``inotify_init1()``. Raises ``OSError`` on failure. :func:`~inotify_simple.INotify.close` should be called when no longer needed. Can be used as a context manager to ensure it is closed, and can be used directly by functions expecting a file-like object, such as ``select``, or with functions expecting a file descriptor via :func:`~inotify_simple.INotify.fileno`. Args: inheritable (bool): whether the inotify file descriptor will be inherited by child processes. The default,``False``, corresponds to passing the ``IN_CLOEXEC`` flag to ``inotify_init1()``. Setting this flag when opening filedescriptors is the default behaviour of Python standard library functions since PEP 446. nonblocking (bool): whether to open the inotify file descriptor in nonblocking mode, corresponding to passing the ``IN_NONBLOCK`` flag to ``inotify_init1()``. This does not affect the normal behaviour of :func:`~inotify_simple.INotify.read`, which uses ``poll()`` to control blocking behaviour according to the given timeout, but will cause other reads of the file descriptor (for example if the application reads data manually with ``os.read(fd)``) to raise ``BlockingIOError`` if no data is available.""" global _libc _libc = _libc or cdll.LoadLibrary('libc.so.6') flags = (not inheritable) * CLOEXEC | bool(nonblocking) * NONBLOCK FileIO.__init__(self, _libc_call(_libc.inotify_init1, flags), mode='rb') self._poller = poll() self._poller.register(self.fileno())
def __init__(self, filename, nstates, natoms, vendor='PyMOL', box=None): file.__init__(self, filename, 'wb') self.natoms = natoms self.fmt = '%df' % (natoms) charmm = int(nstates > 0) # Header fmt='4s 9i d 9i' header = [b'CORD', # 4s nstates, 1, 1, 0, 0, 0, 0, 0, 0, # 9i 1.0, # d 0, 0, 0, 0, 0, 0, 0, 0, 0, # 9i ] if charmm: # DELTA is stored as a double with X-PLOR but as a float with CHARMm fmt = '4s 9i f 10i' header.append(24) # dummy charmm version number self.writeFortran(header,fmt) # Title fmt = 'i80s80s' title = [2, # 1i b'* TITLE'.ljust(80), # 80s (b'* Created by ' + vendor.encode()).ljust(80), # 80s ] self.writeFortran(title,fmt,length=160+4) # NATOM self.writeFortran([natoms],'i')
def __init__(self, name: str = None, mode: str = 'r', prefix: str = None, suffix: str = None, root: str = '/tmp/pyobs/', mkdir: bool = True, *args, **kwargs): """Open/create a temp file. Args: name: Name of file. mode: Open mode. prefix: Prefix for automatic filename creation in write mode. suffix: Suffix for automatic filename creation in write mode. root: Temp directory. mkdir: Whether to automatically create directories. """ # no root given? if root is None: raise ValueError('No root directory given.') # create root? if not os.path.exists(root): os.makedirs(root) # no filename? if name is None: # cannot read from non-existing filename if 'r' in mode: raise ValueError('No filename given to read from.') # create new temp file name with NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, dir=root) as tmp: name = os.path.basename(tmp.name) # filename is not allowed to start with a / or contain .. if name.startswith('/') or '..' in name: raise ValueError('Only files within root directory are allowed.') # build filename self.filename = name full_name = os.path.join(root, name) # need to create directory? path = os.path.dirname(full_name) if not os.path.exists(path): if mkdir: os.makedirs(path) else: raise ValueError( 'Cannot write into sub-directory with disabled mkdir option.' ) # init FileIO FileIO.__init__(self, full_name, mode)
def __init__(self, name: str, mode: str = 'r', root: str = None, mkdir: bool = True, *args, **kwargs): """Open a local file. Args: name: Name of file. mode: Open mode. root: Root to prefix name with for absolute path in filesystem. mkdir: Whether or not to create non-existing paths automatically. """ # no root given? if root is None: raise ValueError('No root directory given.') # filename is not allowed to start with a / or contain .. if name.startswith('/') or '..' in name: raise ValueError('Only files within root directory are allowed.') # build filename self.filename = name full_path = os.path.join(root, name) # need to create directory? path = os.path.dirname(full_path) if not os.path.exists(path): if mkdir: os.makedirs(path) else: raise ValueError('Cannot write into sub-directory with disabled mkdir option.') # init FileIO FileIO.__init__(self, full_path, mode)
def __init__(self, name, mode="rb", buffering=0): """file(name[, mode[, buffering]]) -> file object Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. The preferred way to open a file is with the builtin open() function. Add a 'U' to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a '\n' in Python. Also, a file so opened gains the attribute 'newlines'; the value for this attribute is one of None (no newline read yet), '\r', '\n', '\r\n' or a tuple containing all the newline types seen. 'U' cannot be combined with 'w' or '+' mode. """ if six.PY2: FileIO.__init__(self, name, mode, buffering) else: # for python3 we drop buffering FileIO.__init__(self, name, mode) self.lock = _Semaphore() self.__size = None
def __init__(self, filename, nstates=-1, natoms=-1, vendor="PyMOL", box=None): file.__init__(self, filename, "w") self.natoms = natoms self.box = box # Write Trajectory Header Information print("TITLE : Created by %s with %d atoms" % (vendor, natoms), file=self)
def __init__(self, filepath, pos=0, size=-1): FileIO.__init__(self, filepath, 'rb') self.name = os_path.basename(filepath) self.__filepath__ = filepath self.__startpos__ = pos self.__size__ = size self.__currentpos__ = 0 total_size = os_path.getsize(filepath) - pos if self.__size__ > total_size: self.__size__ = total_size
def __init__(self, filename, nstates=-1, natoms=-1, vendor='PyMOL', box=None): file.__init__(self, filename, 'w') self.natoms = natoms self.box = box # Write Trajectory Header Information print('TITLE : Created by %s with %d atoms' % (vendor, natoms), file=self)
def __init__(self, filename, nstates, natoms, vendor='PyMOL', box=None): file.__init__(self, filename, 'wb') self.natoms = natoms self.fmt = '%df' % (natoms) charmm = int(nstates > 0) # Header fmt = '4s 9i d 9i' header = [ b'CORD', # 4s nstates, 1, 1, 0, 0, 0, 0, 0, 0, # 9i 1.0, # d 0, 0, 0, 0, 0, 0, 0, 0, 0, # 9i ] if charmm: # DELTA is stored as a double with X-PLOR but as a float with CHARMm fmt = '4s 9i f 10i' header.append(24) # dummy charmm version number self.writeFortran(header, fmt) # Title fmt = 'i80s80s' title = [ 2, # 1i b'* TITLE'.ljust(80), # 80s (b'* Created by ' + vendor.encode()).ljust(80), # 80s ] self.writeFortran(title, fmt, length=160 + 4) # NATOM self.writeFortran([natoms], 'i')
def __init__(self, fname, endian='@', header_prec='i', *args, **kwargs): """Open a Fortran unformatted file for writing. Parameters ---------- endian : character, optional Specify the endian-ness of the file. Possible values are '>', '<', '@' and '='. See the documentation of Python's struct module for their meanings. The deafult is '>' (native byte order) header_prec : character, optional Specify the precision used for the record headers. Possible values are 'h', 'i', 'l' and 'q' with their meanings from Python's struct module. The default is 'i' (the system's default integer). """ file.__init__(self, fname, *args, **kwargs) self.ENDIAN = endian self.HEADER_PREC = header_prec
def __init__(self, filename, nstates, natoms, vendor="PyMOL", box=None): file.__init__(self, filename, "wb") self.natoms = natoms self.fmt = "%df" % (natoms) charmm = int(nstates > 0) # Header fmt = "4s 9i d 9i" header = [b"CORD", nstates, 1, 1, 0, 0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 4s # 9i # d # 9i if charmm: # DELTA is stored as a double with X-PLOR but as a float with CHARMm fmt = "4s 9i f 10i" header.append(24) # dummy charmm version number self.writeFortran(header, fmt) # Title fmt = "i80s80s" title = [2, b"* TITLE".ljust(80), (b"* Created by " + vendor.encode()).ljust(80)] # 1i # 80s # 80s self.writeFortran(title, fmt, length=160 + 4) # NATOM self.writeFortran([natoms], "i")
def __init__(self, inheritable=False, nonblocking=False): """File-like object wrapping ``inotify_init1()``. Raises ``OSError`` on failure. :func:`~inotify_simple.INotify.close` should be called when no longer needed. Can be used as a context manager to ensure it is closed, and can be used directly by functions expecting a file-like object, such as ``select``, or with functions expecting a file descriptor via :func:`~inotify_simple.INotify.fileno`. Args: inheritable (bool): whether the inotify file descriptor will be inherited by child processes. The default,``False``, corresponds to passing the ``IN_CLOEXEC`` flag to ``inotify_init1()``. Setting this flag when opening filedescriptors is the default behaviour of Python standard library functions since PEP 446. On Python < 3.3, the file descriptor will be inheritable and this argument has no effect, one must instead use fcntl to set FD_CLOEXEC to make it non-inheritable. nonblocking (bool): whether to open the inotify file descriptor in nonblocking mode, corresponding to passing the ``IN_NONBLOCK`` flag to ``inotify_init1()``. This does not affect the normal behaviour of :func:`~inotify_simple.INotify.read`, which uses ``poll()`` to control blocking behaviour according to the given timeout, but will cause other reads of the file descriptor (for example if the application reads data manually with ``os.read(fd)``) to raise ``BlockingIOError`` if no data is available.""" try: libc_so = find_library('c') except RuntimeError: # Python on Synology NASs raises a RuntimeError libc_so = None global _libc _libc = _libc or CDLL(libc_so or 'libc.so.6', use_errno=True) O_CLOEXEC = getattr(os, 'O_CLOEXEC', 0) # Only defined in Python 3.3+ flags = ( not inheritable) * O_CLOEXEC | bool(nonblocking) * os.O_NONBLOCK FileIO.__init__(self, _libc_call(_libc.inotify_init1, flags), mode='rb') self._poller = poll() self._poller.register(self.fileno())
def __init__(self, prog, *args, **kwargs): FileIO.__init__(self, *args, **kwargs) self.prog = prog
def __init__(self, prog, *args, **kwargs): FileIO.__init__(self, *args, **kwargs) self.prog = prog
def __init__(self, name, mode='rb', closefd=True, return_raw=False): FileIO.__init__(self, name, mode=mode, closefd=closefd) self._current_dgram_offset = 0 self._total_dgram_count = None self._return_raw = return_raw
def __init__(self,fname, mode='r'): """Open the file for writing, defaults to native endian.""" FileIO.__init__(self, fname, mode) self.ENDIAN = '@'
def __init__(self, path, mode, callback): FileIO.__init__(self, path, mode) self.seek(0, os.SEEK_END) self.__total = self.tell() self.seek(0) self.__callback = callback