fast counting to the lines of a given filename
    through only reading out a limited buffer
619
def countLines(filename, buf_size=1048576):
    
    f = open(filename)
    try:
        lines = 1
        read_f = f.read  # loop optimization
        buf = read_f(buf_size)
        # Empty file
        if not buf:
            return 0
        while buf:
            lines += buf.count('\n')
            buf = read_f(buf_size)
        return lines
    finally:
        f.close()
579249
def get_lines(filename: str) -> Iterator[str]:
    """"""
    if filename.endswith('.gz'):
        with gzip.open(filename, 'r') as f:
            for line in f:
                yield line.decode('utf-8')
    else:
        with open(filename, 'r', encoding='utf-8') as f:
            for line in f:
                yield line
488411
def SkipAhead(self, file_object, number_of_characters):
    
    lines_size = len(self.lines)
    while number_of_characters >= lines_size:
      number_of_characters -= lines_size

      self.lines = ''
      self.ReadLines(file_object)
      lines_size = len(self.lines)
      if lines_size == 0:
        return

    self.lines = self.lines[number_of_characters:]
126501
function countLines (str) {
  if (str) {
    let lines = str.match(/\n/g);
    if (lines) {
      return lines.length;
    }
  }
  return 0;
}
228589
def _filter_seqs(fn):
    """"""
    out_file = op.splitext(fn)[0] + "_unique.fa"
    idx = 0
    if not file_exists(out_file):
        with open(out_file, 'w') as out_handle:
            with open(fn) as in_handle:
                for line in in_handle:
                    if line.startswith("@") or line.startswith(">"):
                        fixed_name = _make_unique(line.strip(), idx)
                        seq = in_handle.next().strip()
                        counts = _get_freq(fixed_name)
                        if len(seq) < 26 and (counts > 1 or counts == 0):
                            idx += 1
                            print(fixed_name, file=out_handle, end="\n")
                            print(seq, file=out_handle, end="\n")
                        if line.startswith("@"):
                            in_handle.next()
                            in_handle.next()
    return out_file
348304
private int retrieveIndexValueFromFileName(String fileName) {
        int index = 0;
        if (fileName != null && !fileName.trim().isEmpty()) {
            index = Integer.parseInt(fileName.substring(fileName.lastIndexOf('-') + 1,
                    fileName.length() - EXTENSION.length()));
        }
        return index;
    }
844281
def count_lines(fname, mode='rU'):
    '''
    '''

    with open(fname, mode) as f:
        for i, l in enumerate(f):
            pass
    return i + 1
396648
def num_lines(self):
        
        if self.from_stdin:
            return None
        if not self._num_lines:
            self._iterate_lines()
        return self._num_lines
195146
def readlines(self, offset=0):
        """"""
        try:
            with open(self._filepath) as fp:
                # For full read go through existing lines in file
                if self._full_read:
                    fp.seek(offset)
                    for row in fp:
                        yield row

                # Okay now dynamically tail the file
                if self._tail:
                    while True:
                        current = fp.tell()
                        row = fp.readline()
                        if row:
                            yield row
                        else:
                            fp.seek(current)
                            time.sleep(self._sleep)

        except IOError as err:
            print('Error reading the file {0}: {1}'.format(self._filepath, err))
            return
1019015
private List<String> readFile(String fileName) {
        List<String> result = Lists.newArrayList();

        try (BufferedReader bufRead = Files.newBufferedReader(Paths.get(fileName), options.atFileCharset)) {
            String line;
            // Read through file one line at time. Print line # and line
            while ((line = bufRead.readLine()) != null) {
                // Allow empty lines and # comments in these at files
                if (line.length() > 0 && !line.trim().startsWith("#")) {
                    result.add(line);
                }
            }
        } catch (IOException e) {
            throw new ParameterException("Could not read file " + fileName + ": " + e);
        }

        return result;
    }
461479
def evaluate(self, filename):
		""""""
		with open(filename, 'r') as infile:
			lines = infile.read().splitlines()

			lemma_count = 0
			token_count = 0

			for line in lines:
				line = re.sub(r'[.,!?:;0-9]', ' ', line)
				lemmas = [lemma for (_, lemma) in self.lemmatize(line, best_guess=False)]

				token_count += len(lemmas)
				lemma_count += len(lemmas) - lemmas.count([])

			return lemma_count/token_count
1018706
def read_from_file(filename):
        
        with open(filename) as f:
            result = CP2KInputFile()
            try:
                while True:
                    result.load_children(f)
            except EOFError:
                pass
        return result
591627
private int parseFileIndex(String fileName) {
    Matcher match = null;
    String indexString = null;
    try {
      match = exportPattern.matcher(fileName);
      match.find();
      indexString = match.group(1);
    } catch (Exception e) {
      throw new IllegalStateException(String.format("Failed to parse file '%s'", fileName), e);
    }
    long longValue = Long.parseLong(indexString);
    if (longValue > Integer.MAX_VALUE) {
      throw new IndexOutOfBoundsException(String.format(
          "Invalid fileName '%s'; max allowable index is %d, got %d instead",
          fileName, Integer.MAX_VALUE, longValue));
    }
    return (int) longValue;
  }
1182659
def read_extra_lines(self, filename):
        
        data = np.atleast_2d(np.loadtxt(filename))
        for nr, coords in enumerate(data):
            p1 = [coords[0], coords[1]]
            p2 = [coords[2], coords[3]]
            index = self.add_line(p1, p2, self.char_lengths['extra_line'])
            self.ExtraLineIndices.append(index)
774691
private static int countWildcardPhraseFrequencies(File dir, String pattern)
        throws Exception {
        
        File[] files = dir.listFiles();

        int total = 0;

        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (f.isDirectory()) {
                total += countWildcardPhraseFrequencies(f, pattern);
            } else if (f.getName().endsWith(".txt")) {
                Scanner sc = new Scanner(f);
                while (sc.hasNext()) {
                    String line = sc.nextLine();
                    if (line.matches(pattern)) {
                        total++;
                    }
                }
            }
        }
        return total;
    }
910560
def _read_file(self, filename):
        """"""
        result = []
        with open(filename, 'r') as f:
            lines = f.read().split('\n')
            for line in lines:
                nocomment = line.strip().split('#')[0].strip()
                if nocomment:
                    result.append(nocomment)
        return result
112542
def _readfname(fname):
    """"""
    try:
        if isinstance(fname, (file, StringIO)):
            astr = fname.read()
        else:
            astr = open(fname, 'rb').read()
    except NameError:
        if isinstance(fname, (FileIO, StringIO)):
            astr = fname.read()
        else:
            astr = mylib2.readfile(fname)
    return astr