Create a text from a file.

        Args:
            path (str): The file path.
763031
def from_file(cls, path):

        

        with open(path, 'r', errors='replace') as f:
            return cls(f.read())
844576
def read_file(path):
    
    with open(must_exist(path)) as infile:
        r = infile.read()
    return r
881846
def generate(self, path, label):
        
        for filename in os.listdir(path):
            self[filename] = label
15926
def to_file(self, path, mode="w"):
        
        with open(path, mode=mode) as f:
            for tree in self:
                for label, line in tree.to_labeled_lines():
                    f.write(line + "\n")
1153239
def _create_file(path=''):
        '''  '''
        from os.path import isfile
        if not isfile(path): # only do the following if the file doesn't exist yet
            from os import chmod
            from stat import S_IRUSR, S_IWUSR

            open(path, "a").close()  # create the file
            attempt(lambda: chmod(path, (S_IRUSR | S_IWUSR)))
943166
def path_to_url(path):
    # type: (Union[str, Text]) -> str
    
    path = os.path.normpath(os.path.abspath(path))
    url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path))
    return url
29836
def from_path(cls, path: pathlib.Path) -> 'File':
        
        if not path.is_file():
            raise ValueError('Path does not point to a file')
        return File(path.name, path.stat().st_size, cls._md5(path))
982485
def from_file(cls, path, environ):
        
        instance = cls()
        instance.read(path, environ)
        return instance
1300414
def load_file_to_str(path):
    # type: (str) -> str
    
    with open(path, 'rt') as f:
        string = f.read().replace(linesep, '')
    if not string:
        raise LoadError('%s file is empty!' % path)
    return string
1345715
def ascii_bytes_from(path, *paths):
    
    file_path = os.path.join(path, *paths)
    with open(file_path) as f:
        ascii_bytes = f.read()
    return ascii_bytes
676559
def write_file(content, *path):
    
    with open(os.path.join(*path), "w") as file:
        return file.write(content)
1262899
def loadtxt_str(path:PathOrStr)->np.ndarray:
    ""
    with open(path, 'r') as f: lines = f.readlines()
    return np.array([l.strip() for l in lines])
146519
def create(self, path: str, k: int = 20):
        
        self.lex = np.zeros((len(self.vocab_source), k), dtype=np.int)
        src_unk_id = self.vocab_source[C.UNK_SYMBOL]
        trg_unk_id = self.vocab_target[C.UNK_SYMBOL]
        num_insufficient = 0  # number of source tokens with insufficient number of translations given k
        for src_id, group in groupby(lexicon_iterator(path, self.vocab_source, self.vocab_target), key=itemgetter(0)):
            # Unk token will always be part of target vocab, so no need to track it here
            if src_id == src_unk_id:
                continue

            # filter trg_unk_id
            filtered_group = ((trg_id, prob) for src_id, trg_id, prob in group if trg_id != trg_unk_id)
            # sort by prob and take top k
            top_k = [trg_id for trg_id, prob in sorted(filtered_group, key=itemgetter(1), reverse=True)[:k]]
            if len(top_k) < k:
                num_insufficient += 1

            self.lex[src_id, :len(top_k)] = top_k

        logger.info("Created top-k lexicon from \"%s\", k=%d. %d source tokens with fewer than %d translations",
                    path, k, num_insufficient, k)
905860
private File createNewFile(String path) throws IOException {

		// In windows, pathnames with spaces are returned as %20
		if (path.contains("%20"))
			path = path.replaceAll("%20", " ");
		File newFile = new File(path);

		if (!newFile.exists() && !newFile.createNewFile()) {
			throw new BundlingProcessException("Unable to create a temporary file at " + path);
		}

		if (LOGGER.isDebugEnabled())
			LOGGER.debug("Created file: " + newFile.getCanonicalPath());
		return newFile;
	}
755817
def load(self, path):
        
        self.dct = wrapper.Dictionary()
        self.guide = wrapper.Guide()

        with open(path, 'rb') as f:
            self.dct.read(f)
            self.guide.read(f)

        return self
1357519
def dump(self, path):
        
        try:
            with open(path, "wb") as f:
                f.write(self.__str__().encode("utf-8"))
        except:
            pass

        with open(path, "wb") as f:
            pickle.dump(self.__data__, f)
1299951
def from_file(cls, path=None):
        
        # None => use default
        if path is None:
            for path in cls.default_pathes():
                try:
                    return cls.from_file(path)
                except IOError as e:
                    logging.getLogger(__name__).debug(
                        _("Failed to read config file: {0}", exc_message(e)))
                except ImportError as e:
                    logging.getLogger(__name__).warn(
                        _("Failed to read {0!r}: {1}", path, exc_message(e)))
            return cls({})
        # False/'' => no config
        if not path:
            return cls({})
        if os.path.splitext(path)[1].lower() == '.json':
            from json import load
        else:
            from yaml import safe_load as load
        with open(path) as f:
            return cls(load(f))