Read in txt files.

        Method for reading in text or csv files. This uses ascii class from astropy.io
        for flexible input. It is slower than numpy, but has greater flexibility with less input.
496578
def txt_read_in(self):
        

        # read in
        data = ascii.read(self.WORKING_DIRECTORY + '/' + self.file_name)

        # find number of distinct x and y points.
        num_x_pts = len(np.unique(data[self.x_column_label]))
        num_y_pts = len(np.unique(data[self.y_column_label]))

        # create 2D arrays of x,y,z
        self.xvals = np.reshape(np.asarray(data[self.x_column_label]), (num_y_pts, num_x_pts))
        self.yvals = np.reshape(np.asarray(data[self.y_column_label]), (num_y_pts, num_x_pts))
        self.zvals = np.reshape(np.asarray(data[self.z_column_label]), (num_y_pts, num_x_pts))

        return
556694
def _input_file_as_lines(cls, session: AppSession):
        ''''''
        if session.args.input_file == sys.stdin:
            input_file = session.args.input_file
        else:
            reader = codecs.getreader(session.args.local_encoding or 'utf-8')
            input_file = reader(session.args.input_file)

        return input_file
850410
def _imread(self, file):
        """"""
        # For now, we have to select the imageio plugin to read image from byte stream
        # When ski-image v0.15 is released, imageio will be the default plugin, so this
        # code can be simplified at that time.  See issue report and pull request:
        # https://github.com/scikit-image/scikit-image/issues/2889
        # https://github.com/scikit-image/scikit-image/pull/3126
        img = skimage_io.imread(file, as_gray=self.as_gray, plugin='imageio')
        if img is not None and len(img.shape) != 2:
            # The PIL plugin somewhy fails to load some images
            img = skimage_io.imread(file, as_gray=self.as_gray, plugin='matplotlib')
        return img
46784
def read(self, *files, **params):
        
        for f in files:
            try:
                with io.open(f, encoding='utf-8') as ff:
                    NS_LOGGER.info('Read from `{0}`'.format(ff.name))
                    self.parse(ff.read(), **params)
            except (IOError, TypeError, SyntaxError, io.UnsupportedOperation):
                if not self.silent_read:
                    NS_LOGGER.error('Reading error `{0}`'.format(ff.name))
                    raise
1237483
def read_dict_from_properties(desired_type: Type[dict], file_object: TextIOBase,
                              logger: Logger, conversion_finder: ConversionFinder, **kwargs) -> Dict[str, Any]:
    

    # right now jprops relies on a byte stream. So we convert back our nicely decoded Text stream to a unicode
    # byte stream ! (urgh)
    class Unicoder:
        def __init__(self, file_object):
            self.f = file_object

        def __iter__(self):
            return self

        def __next__(self):
            line = self.f.__next__()
            return line.encode(encoding='utf-8')

    res = jprops.load_properties(Unicoder(file_object))

    # first automatic conversion of strings > numbers
    res = {key: try_parse_num_and_booleans(val) for key, val in res.items()}

    # further convert if required
    return ConversionFinder.convert_collection_values_according_to_pep(res, desired_type, conversion_finder, logger, 
                                                                       **kwargs)
1195821
public void readData(BufferedReader in) throws IOException {
    final String SEEN = "SEEN";
    String line;
    int lineNum = 1;
    // all lines have one tagging with raw count per line
    line = in.readLine();
    Pattern p = Pattern.compile("^smooth\\[([0-9])\\] = (.*)$");
    while (line != null && line.length() > 0) {
      try {
        Matcher m = p.matcher(line);
        if (m.matches()) {
          int i = Integer.parseInt(m.group(1));
          smooth[i] = Double.parseDouble(m.group(2));
        } else {
          // split on spaces, quote with doublequote, and escape with backslash
          String[] fields = StringUtils.splitOnCharWithQuoting(line, ' ', '\"', '\\');
          // System.out.println("fields:\n" + fields[0] + "\n" + fields[1] +
          // "\n" + fields[2] + "\n" + fields[3] + "\n" + fields[4]);
          boolean seen = fields[3].equals(SEEN);
          addTagging(seen, new IntTaggedWord(fields[2], fields[0], wordIndex, tagIndex), Double.parseDouble(fields[4]));
        }
      } catch (RuntimeException e) {
        throw new IOException("Error on line " + lineNum + ": " + line, e);
      }
      lineNum++;
      line = in.readLine();
    }
    initRulesWithWord();
  }
90582
def read_text_file(filename, encoding="utf-8"):
    
    try:
        with open(filename, 'r', encoding) as f:
            r = f.read()
    except TypeError:
        with open(filename, 'r') as f:
            r = f.read()
    return r
331381
private ExampleSet readDataSet(File in) throws IOException {
        logger.info("read the example set");

        //
        logger.info("read data set");
        ExampleSet inputSet = new SentenceSetCopy();
        inputSet.read(new BufferedReader(new FileReader(in)));

        return inputSet;
    }
274387
private ExampleSet readDataSet(File in) throws IOException {
        logger.info("read the example set");

        //
        ExampleSet inputSet1 = new SentenceSetCopy();
        inputSet1.read(new BufferedReader(new FileReader(in)));

        return inputSet1;
    }
1114858
def _read(self, filename, field_labels=None):
        
        # if fields is None, all fields are read
        def read_field(f):
            """Read a single field"""
            datatype = None
            while datatype is None:
                # find a sane header line
                line = f.readline()
                if line == "":
                    return False

                label = line[:43].strip()
                if field_labels is not None:
                    if len(field_labels) == 0:
                        return False
                    elif label not in field_labels:
                        return True
                    else:
                        field_labels.discard(label)
                line = line[43:]
                words = line.split()
                if len(words) == 0:
                    return True

                if words[0] == 'I':
                    datatype = int
                    unreadable = 0
                elif words[0] == 'R':
                    datatype = float
                    unreadable = np.nan

            if len(words) == 2:
                try:
                    value = datatype(words[1])
                except ValueError:
                    return True
            elif len(words) == 3:
                if words[1] != "N=":
                    raise FileFormatError("Unexpected line in formatted checkpoint file %s\n%s" % (filename, line[:-1]))
                length = int(words[2])
                value = np.zeros(length, datatype)
                counter = 0
                try:
                    while counter < length:
                        line = f.readline()
                        if line == "":
                            raise FileFormatError("Unexpected end of formatted checkpoint file %s" % filename)
                        for word in line.split():
                            try:
                                value[counter] = datatype(word)
                            except (ValueError, OverflowError) as e:
                                print('WARNING: could not interpret word while reading %s: %s' % (word, self.filename))
                                if self.ignore_errors:
                                    value[counter] = unreadable
                                else:
                                    raise
                            counter += 1
                except ValueError:
                    return True
            else:
                raise FileFormatError("Unexpected line in formatted checkpoint file %s\n%s" % (filename, line[:-1]))

            self.fields[label] = value
            return True

        self.fields = {}
        with open(filename, 'r') as f:
            self.title = f.readline()[:-1].strip()
            words = f.readline().split()
            if len(words) == 3:
                self.command, self.lot, self.basis = words
            elif len(words) == 2:
                self.command, self.lot = words
            else:
                raise FileFormatError('The second line of the FCHK file should contain two or three words.')

            while read_field(f):
                pass
809728
def read(self, file, nbytes):
        """"""
        if not capable.OF_GRAPHICS:
            raise RuntimeError("Cannot run this command without graphics")
        if isinstance(file, int):
            fd = file
        else:
            # Otherwise, assume we have Python file object
            try:
                fd = file.fileno()

            except:
                raise TypeError("file must be an integer or a filehandle/socket")
        init_tk_default_root() # harmless if already done
        self.widget = TKNTR._default_root
        if not self.widget:
            # no Tk widgets yet, so no need for mainloop
            # (shouldnt happen now with init_tk_default_root)
            s = []
            while nbytes>0:
                snew = os.read(fd, nbytes) # returns bytes in PY3K
                if snew:
                    if PY3K: snew = snew.decode('ascii','replace')
                    s.append(snew)
                    nbytes -= len(snew)
                else:
                    # EOF -- just return what we have so far
                    break
            return "".join(s)
        else:
            self.nbytes = nbytes
            self.value = []
            self.widget.tk.createfilehandler(fd,
                                    TKNTR.READABLE | TKNTR.EXCEPTION,
                                    self._read)
            try:
                self.widget.mainloop()
            finally:
                self.widget.tk.deletefilehandler(fd)
            return "".join(self.value)
661934
def read_csv(csvfile, options):
    

    # open file or exit
    name, ext = os.path.splitext(csvfile)
    try:
        if ext == '.gz':
            f = gzip.open(csvfile, 'rb')
        else:
            f = open(csvfile, 'rU')
    except IOError:
        print(" \n '{f}' could not be opened\n".format(f=os.path.basename(csvfile)))
        sys.exit(1)

    # read file
    csv_reader = csv.reader(f)
    molList = []
    linenumber = 1

    for line in csv_reader:
        # get column labels from the first line
        if linenumber == 1:
            prop_indices = read_header(line, options)

        # otherwise read line & append to MolList
        else:
            mol = Molecule()
            mol = read_line(line, options, prop_indices, mol)
            # if the line's junk, skip it
            if mol == 1:
                print(" skipping molecule 'm'\n".format(m=(linenumber - 1)))
            else:
                molList.append(mol)

        linenumber += 1

    # return molList

    return molList
1223486
def read_atsplib(filename):
    ""
    "NOTE: only works for explicit matrices"

    if filename[-3:] == ".gz":
        f = gzip.open(filename, 'r')
        data = f.readlines()
    else:
        f = open(filename, 'r')
        data = f.readlines()

    for line in data:
        if line.find("DIMENSION") >= 0:
            n = int(line.split()[1])
            break
    else:
        raise IOError("'DIMENSION' keyword not found in file '%s'" % filename)

    for line in data:
        if line.find("EDGE_WEIGHT_TYPE") >= 0:
            if line.split()[1] == "EXPLICIT":
                break
    else:
        raise IOError("'EDGE_WEIGHT_TYPE' is not 'EXPLICIT' in file '%s'" % filename)

    for k,line in enumerate(data):
        if line.find("EDGE_WEIGHT_SECTION") >= 0:
            break
    else:
        raise IOError("'EDGE_WEIGHT_SECTION' not found in file '%s'" % filename)

    c = {}
    # flatten list of distances
    dist = []
    for line in data[k+1:]:
        if line.find("EOF") >= 0:
            break
        for val in line.split():
            dist.append(int(val))

    k = 0
    for i in range(n):
        for j in range(n):
            c[i+1,j+1] = dist[k]
            k += 1

    return n,c
827268
def register_ascii_series_io(array_type, format='txt', identify=True,
                             **defaults):
    
    def _read(filepath, **kwargs):
        kwgs = defaults.copy()
        kwgs.update(kwargs)
        return read_ascii_series(filepath, array_type=array_type, **kwgs)

    def _write(series, output, **kwargs):
        kwgs = defaults.copy()
        kwgs.update(kwargs)
        return write_ascii_series(series, output, **kwgs)

    io_registry.register_reader(format, array_type, _read)
    io_registry.register_writer(format, array_type, _write)
    if identify:
        io_registry.register_identifier(format, array_type,
                                        identify_factory(format))
694981
def _text_or_file(input_):
    '''
    
    '''
    if _isfile(input_):
        with salt.utils.files.fopen(input_) as fp_:
            out = salt.utils.stringutils.to_str(fp_.read())
    else:
        out = salt.utils.stringutils.to_str(input_)

    return out
916646
def read_file(self):
        
        with open(self.filename, mode='r+', encoding='utf8') as text_file:
            self.raw_file = text_file.read()  # pylint: disable= attribute-defined-outside-init
        self.file_lines = [x.rstrip() for x in self.raw_file.splitlines()]
1181983
def load_any_file(filename):
    
    import f311

    # Splits attempts using ((binary X text) file) criterion
    if a99.is_text_file(filename):
        return load_with_classes(filename, f311.classes_txt())
    else:
        return load_with_classes(filename, f311.classes_bin())