Python save file

60 Python code examples are found related to " save file". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: __init__.py    From CanCat with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def saveSessionToFile(self, filename=None):
        '''
        Saves the current analysis session to the filename given
        If saved previously, the name will already be cached, so it is 
        unnecessary to provide it again.
        '''
        if filename != None:
            self._filename = filename
        elif self._filename == None:
            raise Exception('Cannot save to file when no filename given (and first time save)')
        else:
            filename = self._filename

        savegame = self.saveSession()
        me = pickle.dumps(savegame)

        outfile = file(filename, 'w')
        outfile.write(me)
        outfile.close() 
Example 2
Source File: logconfigreader.py    From crazyflie-clients-python with GNU General Public License v2.0 6 votes vote down vote up
def saveLogConfigFile(self, logconfig):
        """Save a log configuration to file"""
        filename = cfclient.config_path + "/log/" + logconfig.name + ".json"
        logger.info("Saving config for [%s]", filename)

        # Build tree for JSON
        saveConfig = {}
        logconf = {'logblock': {'variables': []}}
        logconf['logblock']['name'] = logconfig.name
        logconf['logblock']['period'] = logconfig.period_in_ms
        # Temporary until plot is fixed

        for v in logconfig.variables:
            newC = {}
            newC['name'] = v.name
            newC['stored_as'] = v.stored_as_string
            newC['fetch_as'] = v.fetch_as_string
            newC['type'] = "TOC"
            logconf['logblock']['variables'].append(newC)

        saveConfig['logconfig'] = logconf

        json_data = open(filename, 'w')
        json_data.write(json.dumps(saveConfig, indent=2))
        json_data.close() 
Example 3
Source File: Exporter.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def fileSaveDialog(self, filter=None, opts=None):
        ## Show a file dialog, call self.export(fileName) when finished.
        if opts is None:
            opts = {}
        self.fileDialog = FileDialog()
        self.fileDialog.setFileMode(QtGui.QFileDialog.AnyFile)
        self.fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        if filter is not None:
            if isinstance(filter, basestring):
                self.fileDialog.setNameFilter(filter)
            elif isinstance(filter, list):
                self.fileDialog.setNameFilters(filter)
        global LastExportDirectory
        exportDir = LastExportDirectory
        if exportDir is not None:
            self.fileDialog.setDirectory(exportDir)
        self.fileDialog.show()
        self.fileDialog.opts = opts
        self.fileDialog.fileSelected.connect(self.fileSaveFinished)
        return 
Example 4
Source File: Flowchart.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def saveFile(self, fileName=None, startDir=None, suggestedFileName='flowchart.fc'):
        if fileName is None:
            if startDir is None:
                startDir = self.filePath
            if startDir is None:
                startDir = '.'
            self.fileDialog = FileDialog(None, "Save Flowchart..", startDir, "Flowchart (*.fc)")
            #self.fileDialog.setFileMode(QtGui.QFileDialog.AnyFile)
            self.fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) 
            #self.fileDialog.setDirectory(startDir)
            self.fileDialog.show()
            self.fileDialog.fileSelected.connect(self.saveFile)
            return
            #fileName = QtGui.QFileDialog.getSaveFileName(None, "Save Flowchart..", startDir, "Flowchart (*.fc)")
        fileName = unicode(fileName)
        configfile.writeConfigFile(self.saveState(), fileName)
        self.sigFileSaved.emit(fileName) 
Example 5
Source File: ml_model_common.py    From resilient-community-apps with MIT License 6 votes vote down vote up
def save_to_file(self, file_name):
        """
        Save this model to a file using pickle.

        :param file_name:   Name of the file to be used for saving
        :return:
        """
        #
        #   No need to save these. They are not used in prediction
        #
        self.X_test = None
        self.X = None
        self.y = None
        self.X_train = None
        self.y_train = None
        self.y_test = None
        self.df = None
        self.log = None

        pickle.dump(self, open(file_name, "wb")) 
Example 6
Source File: client.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def save_to_well_known_file(credentials, well_known_file=None):
    """Save the provided GoogleCredentials to the well known file.

    Args:
        credentials: the credentials to be saved to the well known file;
                     it should be an instance of GoogleCredentials
        well_known_file: the name of the file where the credentials are to be
                         saved; this parameter is supposed to be used for
                         testing only
    """
    # TODO(orestica): move this method to tools.py
    # once the argparse import gets fixed (it is not present in Python 2.6)

    if well_known_file is None:
        well_known_file = _get_well_known_file()

    config_dir = os.path.dirname(well_known_file)
    if not os.path.isdir(config_dir):
        raise OSError(
            'Config directory does not exist: {0}'.format(config_dir))

    credentials_data = credentials.serialization_data
    _save_private_file(well_known_file, credentials_data) 
Example 7
Source File: import_menu.py    From dot15926 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def SaveMappingToFile(self):
        if self.patterns.currentIndex() != 0:
            pattern, option = self.options_list[self.patterns.itemData(self.patterns.currentIndex())][1:]
            pattern_name = pattern.name
            option_name = option.name

            mapping = self.GetRoleMapping()

            data = {'version': 0, 'pattern': pattern_name, 'option': option_name, 'roles': mapping}

            path, wildcard = SelectFiles(tm.ext.patterns_save_mapping, save = True, wildcard = '.json file (*.json)')
            if path:
                try:
                    with open(path, 'w') as f:
                        json.dump(data, f, 'utf-8', ensure_ascii=True)
                except:
                    Notify(tm.ext.patterns_err_save) 
Example 8
Source File: main.py    From suplemon with MIT License 6 votes vote down vote up
def save_file(self, file=False, overwrite=False):
        """Save current file."""
        f = file or self.get_file()
        # Make sure the file has a name
        if not f.get_name():
            return self.save_file_as(f)
        # Warn if the file has changed on disk
        if not overwrite and f.is_changed_on_disk():
            if not self.ui.query_bool("The file was modified since you opened it, save anyway?"):
                return False
        # Save the file
        if f.save():
            self.set_status("Saved [{0}] '{1}'".format(helpers.curr_time_sec(), f.name))
            if f.path() == self.config.path() or f.path() == self.config.keymap_path():
                self.reload_config()
            return True
        self.set_status("Couldn't write to '{0}'".format(f.name))
        return False 
Example 9
Source File: main.py    From suplemon with MIT License 6 votes vote down vote up
def save_file_as(self, file=False):
        """Save current file."""
        f = file or self.get_file()
        name_input = self.ui.query_file("Save as:", f.name)
        if not name_input:
            return False

        target_dir, name = helpers.parse_path(name_input)
        full_path = os.path.join(target_dir, name)

        if os.path.exists(full_path):
            if not self.ui.query_bool("A file or directory with that name already exists. Overwrite it?"):
                return False
        if target_dir and not os.path.exists(target_dir):
            if self.ui.query_bool("The path doesn't exist, do you want to create it?"):
                self.logger.debug("Creating missing folders in save path.")
                os.makedirs(target_dir)
            else:
                return False
        f.set_path(full_path)
        # We can just overwrite the file since the user already confirmed
        return self.save_file(f, overwrite=True) 
Example 10
Source File: file_handling.py    From props with MIT License 6 votes vote down vote up
def save_verbal_predicates_to_file(inp,out):
    f = open(out,'w')
    counter = 0
    dep_trees = dependency_tree.tree_readers.read_trees_file(inp)
    
    for tree in dep_trees:
        
        for verb_subtree in tree.collect_verbal_predicates():
            print counter
            f.write(verb_subtree.to_original_format(root=True)+"\n")
            counter+=1
            
            
    f.close()
    
# load dependency trees from file inp 
Example 11
Source File: serviceFile.py    From subtitle-translator with GNU General Public License v3.0 6 votes vote down vote up
def saveToFile(self, subs, languageDest, isBilingual=False):
        '''
        把当前实例对应的文件名和目标语种做相应处理后,把当前实例
        的items保存到文件中

        '''
        try:

            newStr = '-'+languageDest+self.fileExt if isBilingual == False else '-' + \
                languageDest+"-Bilingual"+self.fileExt
            targetFilePath = self.filePath.replace(self.fileExt, newStr, -1)
            print(targetFilePath)
            subs.save(targetFilePath, encoding='utf-8')
            return True
        except:
            return False 
Example 12
Source File: simple_todo_list.py    From py_cui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def save_todo_file(self):
        """Save the three lists in a specific format
        """

        if os.path.exists('TODO.txt'):
            os.remove('TODO.txt')
        todo_fp = open('TODO.txt', 'w')
        todo_items = self.todo_scroll_cell.get_item_list()
        in_progress_items = self.in_progress_scroll_cell.get_item_list()
        done_items = self.done_scroll_cell.get_item_list()
        for item in todo_items:
            todo_fp.write(item + '\n')
        todo_fp.write('__IN_PROGRESS__' + '\n')
        for item in in_progress_items:
            todo_fp.write(item + '\n')
        todo_fp.write('__DONE__' + '\n')
        for item in done_items:
            todo_fp.write(item + '\n')
        todo_fp.close()
        self.master.show_message_popup('Saved', 'Your TODO list has been saved!')


# Create the CUI, pass it to the wrapper object, and start it 
Example 13
Source File: refresh_token.py    From ec3 with Apache License 2.0 6 votes vote down vote up
def save_token_to_auth_file(self, auth_file, access_token):
        with open(auth_file, 'r') as f:
            auth_data = f.read()

        # replace old token with new one
        new_auth = ""
        for line in auth_data.split("\n"):
            if "OpenStack" in line:
                    pos_ini = line.find("password = ") + 11
                    new_auth += line[:pos_ini] + access_token
                    pos_end = max(line.find(";", pos_ini), line.find("\n", pos_ini))
                    if pos_end > -1:
                        new_auth += line[pos_end:]
                    new_auth += "\n"
            else:
                new_auth += line + "\n"

        with open(auth_file, 'w') as f:
            f.write(new_auth) 
Example 14
Source File: CustomClass.py    From GeoPyTool with GNU General Public License v3.0 6 votes vote down vote up
def saveDataFile(self):

        # if self.model._changed == True:
        # print('changed')
        # print(self.model._df)

        DataFileOutput, ok2 = QFileDialog.getSaveFileName(self,
                                                          '文件保存',
                                                          'C:/',
                                                          'Excel Files (*.xlsx);;CSV Files (*.csv)')  # 数据文件保存输出

        if "Label" in self.model._df.columns.values.tolist():
            self.model._df = self.model._df.set_index('Label')

        if (DataFileOutput != ''):

            if ('csv' in DataFileOutput):
                self.model._df.to_csv(DataFileOutput, sep=',', encoding='utf-8')

            elif ('xls' in DataFileOutput):
                self.model._df.to_excel(DataFileOutput, encoding='utf-8') 
Example 15
Source File: infinite_jukebox.py    From Remixatron with Apache License 2.0 6 votes vote down vote up
def save_to_file(jukebox, label, duration):
    ''' Save a fixed length of audio to disk. '''

    avg_beat_duration = 60 / jukebox.tempo
    num_beats_to_save = int(duration / avg_beat_duration)

    # this list comprehension returns all the 'buffer' arrays from the beats
    # associated with the [0..num_beats_to_save] entries in the play vector

    main_bytes = [jukebox.beats[v['beat']]['buffer'] for v in jukebox.play_vector[0:num_beats_to_save]]

    # main_bytes is an array of byte[] arrays. We need to flatten it to just a
    # regular byte[]

    output_bytes = np.concatenate( main_bytes )

    # write out the wav file
    sf.write(label + '.wav', output_bytes, jukebox.sample_rate, format='WAV', subtype='PCM_24') 
Example 16
Source File: util.py    From TextClassification with MIT License 6 votes vote down vote up
def saveDictToFile(tdict, filename):
    """
    this method will save the key/value pair of the dictionary to a csv file

    Parameters
    ----------
    tdict: dictionary
           dictionary object containing many pairs of key and value
    filename: str
              name of the dictionary file


    Returns
    -------
    """
    import csv
    w = csv.writer(open(filename, "w"))
    for key, val in tdict.items():
        row = []
        row.append(key)
        row.append(val[idx_lbl])
        for cl in class_titles:
            if cl in val:
                row.append(cl + ':' + str(val[cl]))
        w.writerow(row) 
Example 17
Source File: client.py    From data with GNU General Public License v3.0 6 votes vote down vote up
def save_to_well_known_file(credentials, well_known_file=None):
    """Save the provided GoogleCredentials to the well known file.

    Args:
        credentials: the credentials to be saved to the well known file;
                     it should be an instance of GoogleCredentials
        well_known_file: the name of the file where the credentials are to be
                         saved; this parameter is supposed to be used for
                         testing only
    """
    # TODO(orestica): move this method to tools.py
    # once the argparse import gets fixed (it is not present in Python 2.6)

    if well_known_file is None:
        well_known_file = _get_well_known_file()

    config_dir = os.path.dirname(well_known_file)
    if not os.path.isdir(config_dir):
        raise OSError('Config directory does not exist: %s' % config_dir)

    credentials_data = credentials.serialization_data
    _save_private_file(well_known_file, credentials_data) 
Example 18
Source File: io_functions.py    From deepsaber with GNU General Public License v3.0 6 votes vote down vote up
def saveFile(object, filename=None, save_dir=None, append=False):
    if save_dir is None or save_dir is '':
        save_dir = os.path.join(os.getcwd(), 'Temp')
    if not os.path.isdir(save_dir):  # SUBJECT TO RACE CONDITION
        os.mkdir(save_dir)
    if filename is None or filename is '':
        filename = os.path.join(save_dir,
                                getpass.getuser() + '_' + time.strftime('%Y-%m-%d_%H:%M:%S') + '.tmp')
    else:
        filename = os.path.join(save_dir, filename)
    print('Saving file: ' + filename)
    if append is True:
        savefile = open(filename, 'ab')
    else:
        savefile = open(filename, 'wb')
    pickle.dump(object, savefile)
    savefile.close()
    return filename 
Example 19
Source File: core.py    From deen with Apache License 2.0 6 votes vote down vote up
def save_widget_content_to_file(self, file_name=None):
        """Save the content of the current widget
        to a file."""
        focussed_widget = QApplication.focusWidget()
        parent_encoder = self.get_parent_encoder(focussed_widget)
        if not parent_encoder._content:
            return
        fd = QFileDialog(parent_encoder)
        if file_name:
            name = file_name
        else:
            name = fd.getSaveFileName(fd, 'Save File')
        if not name or not name[0]:
            return
        if isinstance(name, tuple):
            name = name[0]
        with open(name, 'wb') as file:
            current_plugin = parent_encoder.plugin
            file.write(parent_encoder._content) 
Example 20
Source File: filestorage.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def save_file(self, filename, file_object, owner):
        """Save the file to the database.

        If a file of that name/owner already existed, it will be replaced by
        the new contents.
        """
        # This probably ought to read in chunks but large files are
        # not expected.
        content = Bin(file_object.read())
        storage, created = self.get_or_create(
            filename=filename, owner=owner, defaults={"content": content}
        )
        if not created:
            storage.content = content
            storage.save()
        return storage 
Example 21
Source File: util_vec.py    From nball4tree with MIT License 6 votes vote down vote up
def save_to_file(dstruc, ofile=""):
    open(ofile, 'w').close()
    with open(ofile, 'a') as ofh:
        if type(dstruc) == dict:
            for k, v in dstruc.items():
                if type(v) == list:
                    ln = ' '.join([k]+v)+'\n'
                if type(v) in [str, int, float]:
                    ln = ' '.join([k, str(v)]) + '\n'
                ofh.write(ln)
        if type(dstruc) == list:
            for ele in dstruc:
                if type(ele) == list:
                    ln = ' '.join(ele)+'\n'
                    ofh.write(ln)
                if type(ele) in [str, int, float]:
                    ofh.write(str(ln)) 
Example 22
Source File: placer.py    From core with MIT License 6 votes vote down vote up
def save_file(self, field=None, file_attrs=None):
        """
        Helper function that moves a file saved via a form field into our CAS.
        May trigger jobs, if applicable, so this should only be called once we're ready for that.

        Requires an augmented file field; see process_upload() for details.
        """

        # Save file
        if field is not None:
            files.move_form_file_field_into_cas(field)

        # Update the DB
        if file_attrs is not None:
            container_before, self.container = hierarchy.upsert_fileinfo(self.container_type, self.id_, file_attrs)

            # Queue any jobs as a result of this upload, uploading to a gear will not make jobs though
            if self.container_type != 'gear':
                rules.create_jobs(config.db, container_before, self.container, self.container_type) 
Example 23
Source File: dataset.py    From models with Apache License 2.0 6 votes vote down vote up
def SaveMetricsFile(mean_average_precision, mean_precisions, mean_recalls,
                    pr_ranks, output_path):
  """Saves aggregated retrieval metrics to text file.

  Args:
    mean_average_precision: Dict mapping each dataset protocol to a float.
    mean_precisions: Dict mapping each dataset protocol to a NumPy array of
      floats with shape [len(pr_ranks)].
    mean_recalls: Dict mapping each dataset protocol to a NumPy array of floats
      with shape [len(pr_ranks)].
    pr_ranks: List of integers.
    output_path: Full file path.
  """
  with tf.io.gfile.GFile(output_path, 'w') as f:
    for k in sorted(mean_average_precision.keys()):
      f.write('{}\n  mAP={}\n  mP@k{} {}\n  mR@k{} {}\n'.format(
          k, np.around(mean_average_precision[k] * 100, decimals=2),
          np.array(pr_ranks), np.around(mean_precisions[k] * 100, decimals=2),
          np.array(pr_ranks), np.around(mean_recalls[k] * 100, decimals=2))) 
Example 24
Source File: Document.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def CheckFileNeedsSave(self):
        """
        Checks if the file was changed and if necessary asks the user if he
        wants to save it. If the user affirms, calls Save/SaveAs also.

        returns: wx.ID_OK     if no save was needed
                 wx.ID_YES    if file was saved
                 wx.ID_NO     if file was not saved
                 wx.ID_CANCEL if user canceled possible save
        """
        if not self.isDirty:
            return wx.ID_OK
        dialog = SaveChangesDialog(self.frame)
        result = dialog.ShowModal()
        dialog.Destroy()
        if result == wx.ID_CANCEL:
            return wx.ID_CANCEL
        elif result == wx.ID_YES:
            return self.Save()
        else:
            return wx.ID_NO 
Example 25
Source File: zoomeye.py    From mec with GNU General Public License v3.0 6 votes vote down vote up
def save_str_to_file(target_file, string):
    '''
    save str to file
    '''

    if not os.path.exists(target_file):
        os.system('touch {}'.format(target_file))
    # check if we are writing duplicate lines to the file
    f_hand = open(target_file)

    for line in f_hand:
        if line.strip() == string:
            return
    # write line to file
    with open(target_file, 'a') as output:
        output.write(string + '\n')
        output.close() 
Example 26
Source File: qiniustorage.py    From flask-blog with MIT License 6 votes vote down vote up
def save_file(self, localfile, filename=None):

        # 构建鉴权对象
        auth = Auth(self._access_key, self._secret_key)
        # 上传到七牛后保存的文件名
        key = filename
        # 生成上传 Token,可以指定过期时间等
        token = auth.upload_token(self._bucket_name)
        ret, info = put_file(token, key, localfile)
        print(info)
        try:
            assert ret['key'] == key
            assert ret['hash'] == etag(localfile)
        except Exception as e:
            current_app.logger.info(e)
        return ret, info 
Example 27
Source File: runTestSuites.py    From nmos-testing with Apache License 2.0 6 votes vote down vote up
def save_test_results_to_file(results, name, folder):
    """Save the JSON test results to the folder"""

    if not folder:
        print('ERROR: No folder specified')
        return
    if not results:
        print('ERROR: No results specified')
        return

    Path(folder).mkdir(parents=True, exist_ok=True)

    filename = "{}{}_{}_{}.json".format(folder, name, results.get('suite'), results.get('timestamp'))

    with open(filename, 'w') as outfile:
        json.dump(results, outfile) 
Example 28
Source File: fileoperations.py    From aws-elastic-beanstalk-cli with Apache License 2.0 6 votes vote down vote up
def save_app_file(app):
    cwd = os.getcwd()
    env_name = app['ApplicationName']
    file_name = env_name + '.app.yml'

    file_name = beanstalk_directory + file_name
    try:
        ProjectRoot.traverse()

        file_name = os.path.abspath(file_name)

        with codecs.open(file_name, 'w', encoding='utf8') as f:
            f.write(safe_dump(app, default_flow_style=False,
                              line_break=os.linesep))

    finally:
        os.chdir(cwd)

    return file_name 
Example 29
Source File: fileoperations.py    From aws-elastic-beanstalk-cli with Apache License 2.0 6 votes vote down vote up
def save_env_file(env):
    cwd = os.getcwd()
    env_name = env['EnvironmentName']
    file_name = env_name + '.env.yml'

    file_name = beanstalk_directory + file_name
    try:
        ProjectRoot.traverse()

        file_name = os.path.abspath(file_name)

        with codecs.open(file_name, 'w', encoding='utf8') as f:
            f.write(safe_dump(env, default_flow_style=False,
                              line_break=os.linesep))

    finally:
        os.chdir(cwd)

    return file_name 
Example 30
Source File: queue.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def save_to_file(self, fp, sep='\n'):
        """
        Read all messages from the queue and persist them to file-like object.
        Messages are written to the file and the 'sep' string is written
        in between messages.  Messages are deleted from the queue after
        being written to the file.
        Returns the number of messages saved.
        """
        n = 0
        m = self.read()
        while m:
            n += 1
            fp.write(m.get_body())
            if sep:
                fp.write(sep)
            self.delete_message(m)
            m = self.read()
        return n 
Example 31
Source File: upload.py    From eoj3 with MIT License 6 votes vote down vote up
def save_uploaded_file_to(file, directory, filename=None, size_limit=None, keep_extension=False):
  """
  :param file: UploadedFile instance
  :param directory: the real dirname of your destination
  :param filename: file name by default
  :param size_limit: by megabytes, exceeding size_limit will raise ValueError
  :param keep_extension: True or False, if you rename your file and filename does not have an extension, the
                         original filename's extension will be used as the new extension. If the original file
                         does not have an extension, then nothing will happen.
  :return: new path
  """
  if size_limit and file.size > size_limit * 1024576:
    raise ValueError("File is too large")
  if keep_extension and filename:
    raw_ext = path.splitext(file.name)[1]
    _, filename_ext = path.splitext(filename)
    if filename_ext != raw_ext:
      filename = filename + raw_ext
  makedirs(directory, exist_ok=True)
  new_path = path.join(directory, filename if filename else file.name)
  with open(new_path, 'wb+') as destination:
    for chunk in file.chunks():
      destination.write(chunk)
  return new_path 
Example 32
Source File: package.py    From eoj3 with MIT License 6 votes vote down vote up
def save_statement_from_file(self, filepath, encoding, language):
    with open(filepath, 'r', encoding=encoding) as statement_file:
      content = statement_file.read()
    statement = Statement(name="pkg_statement", create_time=datetime.now())
    statement.title = content[len('\\begin{problem}{'):content.find('}', len('\\begin{problem}{'))]
    content = content[content.find('\n') + 1:]
    input_format_start = content.find('\\InputFile')
    statement.description = content[:input_format_start]
    content = content[input_format_start:]
    content = content[content.find('\n') + 1:]
    output_format_start = content.find('\\OutputFile')
    statement.input = content[:output_format_start]
    content = content[output_format_start:]
    content = content[content.find('\n') + 1:]
    statement.output = content[:content.find('\\Example')]
    notes_start_pos = content.find('\\Note')
    if notes_start_pos >= 0:
      content = content[notes_start_pos:]
      content = content[content.find('\n') + 1:]
      statement.hint = content[:content.find('\\end{problem}')]
    statement.save()
    self.revision.statements.add(statement)
    self.add_problem_option("active_statement_id", statement.id)
    return True 
Example 33
Source File: GridCalMain.py    From GridCal with GNU General Public License v3.0 6 votes vote down vote up
def save_file_now(self, filename):
        """
        Save the file right now, without questions
        :param filename: filename to save to
        """

        if ('file_save' not in self.stuff_running_now) and ('file_open' not in self.stuff_running_now):
            # lock the ui
            self.LOCK()

            self.save_file_thread_object = FileSaveThread(self.circuit, filename)

            # make connections
            self.save_file_thread_object.progress_signal.connect(self.ui.progressBar.setValue)
            self.save_file_thread_object.progress_text.connect(self.ui.progress_label.setText)
            self.save_file_thread_object.done_signal.connect(self.UNLOCK)
            self.save_file_thread_object.done_signal.connect(self.post_file_save)

            # thread start
            self.save_file_thread_object.start()

            self.stuff_running_now.append('file_save')

        else:
            warning_msg('There is a file being processed..') 
Example 34
Source File: __init__.py    From DynaPhoPy with MIT License 6 votes vote down vote up
def save_mesh_data_to_yaml_file(mesh_data, filename):

    import yaml

    def float_representer(dumper, value):
        text = '{0:.8f}'.format(value)
        return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)

    yaml.add_representer(float, float_representer)

    qpoints, multiplicity, frequencies, linewidths = mesh_data

    output_dict = []
    for i, qp in enumerate(qpoints):
        mesh_dict = {}
        mesh_dict['reduced_wave_vector'] = qp.tolist()
        mesh_dict['frequencies'] = frequencies[i].tolist()
        mesh_dict['linewidths'] = linewidths[i].tolist()
        mesh_dict['multiplicity'] = int(multiplicity[i])

        output_dict.append(mesh_dict)

    with open(filename, 'w') as outfile:
        yaml.dump(output_dict, outfile, default_flow_style=False) 
Example 35
Source File: __init__.py    From DynaPhoPy with MIT License 6 votes vote down vote up
def save_quasiparticle_data_to_file(quasiparticle_data, filename):

    import yaml

    def float_representer(dumper, value):
        text = '{0:.8f}'.format(value)
        return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)

    yaml.add_representer(float, float_representer)

    output_dict = []
    for i, q_point in enumerate(quasiparticle_data['q_points']):
        q_point_dict = {'reduced_wave_vector': q_point.tolist()}
        q_point_dict.update({'frequencies': quasiparticle_data['frequencies'][i].tolist()})
        q_point_dict.update({'linewidths': quasiparticle_data['linewidths'][i].tolist()})
        q_point_dict.update({'frequency_shifts': quasiparticle_data['frequency_shifts'][i].tolist()})
        # output_dict.update({'q_point_{}'.format(i): q_point_dict})
        output_dict.append(q_point_dict)

    with open(filename, 'w') as outfile:
        yaml.dump(output_dict, outfile, default_flow_style=False) 
Example 36
Source File: window.py    From drawing with GNU General Public License v3.0 6 votes vote down vote up
def file_chooser_save(self):
		"""Opens an "save" file chooser dialog, and return a GioFile or None."""
		gfile = None
		file_chooser = Gtk.FileChooserNative.new(_("Save picture as…"), self,
		                     Gtk.FileChooserAction.SAVE, _("Save"), _("Cancel"))
		utilities_add_filechooser_filters(file_chooser)

		images_dir = GLib.get_user_special_dir(GLib.USER_DIRECTORY_PICTURES)
		if images_dir != None: # no idea why it sometimes fails
			file_chooser.set_current_folder(images_dir)
		default_file_name = str(_("Untitled") + '.png')
		file_chooser.set_current_name(default_file_name)

		response = file_chooser.run()
		if response == Gtk.ResponseType.ACCEPT:
			gfile = file_chooser.get_file()
		file_chooser.destroy()
		return gfile 
Example 37
Source File: input_data.py    From honk with MIT License 6 votes vote down vote up
def save_wav_file(filename, wav_data, sample_rate):
  """Saves audio sample data to a .wav audio file.

  Args:
    filename: Path to save the file to.
    wav_data: 2D array of float PCM-encoded audio data.
    sample_rate: Samples per second to encode in the file.
  """
  with tf.Session(graph=tf.Graph()) as sess:
    wav_filename_placeholder = tf.placeholder(tf.string, [])
    sample_rate_placeholder = tf.placeholder(tf.int32, [])
    wav_data_placeholder = tf.placeholder(tf.float32, [None, 1])
    wav_encoder = contrib_audio.encode_wav(wav_data_placeholder,
                                           sample_rate_placeholder)
    wav_saver = io_ops.write_file(wav_filename_placeholder, wav_encoder)
    sess.run(
        wav_saver,
        feed_dict={
            wav_filename_placeholder: filename,
            sample_rate_placeholder: sample_rate,
            wav_data_placeholder: np.reshape(wav_data, (-1, 1))
        }) 
Example 38
Source File: export.py    From renrenBackup with MIT License 6 votes vote down vote up
def save_file(client, url_path):
    logger.debug('try to save {url}'.format(url=url_path))
    local_path = re.sub(r'(/\w*)', r'../', url_path)[:-4]
    if not local_path:
        local_path = '.'

    filename = '.{url_path}.html'.format(url_path=url_path)
    filepath = os.path.dirname(filename)

    resp = client.get(url_path)
    output_html = trans_relative_path(resp.data.decode("utf8"), local_path)

    if not os.path.exists(filepath):
        os.makedirs(filepath)

    with open(filename, 'wb') as fp:
        fp.write(output_html.encode('utf8'))

    return filename 
Example 39
Source File: upload.py    From PowerHub with MIT License 6 votes vote down vote up
def save_file(file, dir=UPLOAD_DIR, encrypted=False):
    """Save a file to the upload directory and return the filename

    If it already exists, append a counter.
    """
    filename = os.path.join(dir, os.path.basename(file.filename))
    if os.path.exists(filename):
        count = 1
        while os.path.isfile("%s.%d" % (filename, count)):
            count += 1
        filename += ".%d" % count
    if encrypted:
        data = file.read()
        data = encrypt(data, KEY)
        with open(filename, 'bw') as f:
            f.write(data)
    else:
        file.save(filename)
    return filename 
Example 40
Source File: tools.py    From Menotexport with GNU General Public License v3.0 6 votes vote down vote up
def saveFile(abpath_out,text,overwrite=True,verbose=True):

    if os.path.isfile(abpath_out):
        if overwrite:
            os.remove(abpath_out)
        else:
            abpath_out=autoRename(abpath_out)

    if verbose:
        print('\n# <saveFile>: Saving result to:')
        print(abpath_out)

    with open(abpath_out, mode='a') as fout:
        fout.write(enu(text))

    return 
Example 41
Source File: ciscoparse.py    From netgrph with GNU Affero General Public License v3.0 6 votes vote down vote up
def save_links_file(data, out_file):

    save = open(out_file, "w")

    linkKeys = []

    # Get Dict keys for CSV Out
    for key in sorted(data[0].keys()):
        if key != "__values__":
            linkKeys.append(key)

    linkWriter = csv.writer(save)
    linkWriter.writerow(linkKeys)

    # Go through all entries and dump them to CSV
    for en in data:
        linkValues = []
        for key in sorted(en.keys()):
            if key != "__values__":
                linkValues.append(en[key])
        # Write Values to CSV
        linkWriter.writerow(linkValues)
    save.close()

# Save vlan data to list 
Example 42
Source File: self_play.py    From alphagozero with MIT License 6 votes vote down vote up
def save_file(model_name, game_n, game_data, winner):
    directory = os.path.join(conf["GAMES_DIR"], model_name)
    os.makedirs(directory, exist_ok=True)
    with h5py.File(os.path.join(directory, GAME_FILE % game_n), 'w') as f:
        f.create_dataset('n_moves', data=(len(game_data['moves']), ), dtype=np.int32)
        for move_data in game_data['moves']:
            board = move_data['board']
            policy_target = move_data['policy']
            player = move_data['player']
            value_target = 1 if winner == player else -1
            move = move_data['move_n']

            grp = f.create_group('move_%s' % move)
            grp.create_dataset('board', data=board, dtype=np.float32)
            grp.create_dataset('policy_target', data=policy_target, dtype=np.float32)
            grp.create_dataset('value_target', data=np.array(value_target), dtype=np.float32)
    with open(os.path.join(directory, MOVE_INDEX), 'a') as f:
        for move_data in game_data['moves']:
            line = [game_n, move_data['move_n'], move_data['policy_variation']]
            f.write(",".join(str(item) for item in line) + "\n") 
Example 43
Source File: TopicPagesExamples.py    From event-registry-python with MIT License 6 votes vote down vote up
def saveAndLoadTopicPageFromFile():
    topic = TopicPage(er)
    topic.addKeyword("renewable energy", 30)

    arts1 = topic.getArticles(page=1)

    # save the definition to a file and later load it
    definition = topic.saveTopicPageDefinitionToFile("topic.json")

    topic2 = TopicPage(er)
    topic2.loadTopicPageFromFile("topic.json")

    arts2 = topic2.getArticles(page=1)

    # arts1 and arts2 should be (almost) the same


# createTopicPage1() 
Example 44
Source File: PLCControler.py    From OpenPLC_Editor with GNU General Public License v3.0 6 votes vote down vote up
def SaveXMLFile(self, filepath=None):
        if not filepath and self.FilePath == "":
            return False
        else:
            contentheader = {"modificationDateTime": datetime.datetime(*localtime()[:6])}
            self.Project.setcontentHeader(contentheader)

            if filepath:
                SaveProject(self.Project, filepath)
            else:
                SaveProject(self.Project, self.FilePath)

            self.MarkProjectAsSaved()
            if filepath:
                self.SetFilePath(filepath)
            return True

    # -------------------------------------------------------------------------------
    #                       Search in Current Project Functions
    # ------------------------------------------------------------------------------- 
Example 45
Source File: io.py    From cvcalib with Apache License 2.0 6 votes vote down vote up
def save_opencv_xml_file(path, xml_generator):
    """
    Save something in opencv's XML format
    @param path: path where to save the file
    @param xml_generator: function that accepts an LXML root element as a parameter and generates all the necessary XML
    to go in the file
    """
    root = etree.Element("opencv_storage")
    xml_generator(root)
    et = etree.ElementTree(root)
    with open(path, 'wb') as f:
        et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)
    # little hack necessary to replace the single quotes (that OpenCV doesn't like) with double quotes
    s = open(path).read()
    s = s.replace("'", "\"")
    with open(path, 'w') as f:
        f.write(s)
        f.flush() 
Example 46
Source File: schematic.py    From MCEdit-Unified with ISC License 6 votes vote down vote up
def saveToFile(self, filename):
        schematicDat = nbt.TAG_Compound()
        schematicDat.name = "Mega Schematic"

        schematicDat["Width"] = nbt.TAG_Int(self.size[0])
        schematicDat["Height"] = nbt.TAG_Int(self.size[1])
        schematicDat["Length"] = nbt.TAG_Int(self.size[2])
        schematicDat["Materials"] = nbt.TAG_String(self.materials.name)

        schematicDat.save(self.worldFolder.getFilePath("schematic.dat"))

        basedir = self.worldFolder.filename
        assert os.path.isdir(basedir)

        with closing(zipfile.ZipFile(filename, "w", zipfile.ZIP_STORED, allowZip64=True)) as z:
            for root, dirs, files in os.walk(basedir):
                # NOTE: ignore empty directories
                for fn in files:
                    absfn = os.path.join(root, fn)
                    shutil.move(absfn, absfn.replace("##MCEDIT.TEMP##" + os.sep, ""))
                    absfn = absfn.replace("##MCEDIT.TEMP##" + os.sep, "")
                    zfn = absfn[len(basedir) + len(os.sep):]  # XXX: relative path
                    z.write(absfn, zfn) 
Example 47
Source File: application.py    From xmind2testcase with MIT License 6 votes vote down vote up
def save_file(file):
    if file and allowed_file(file.filename):
        # filename = check_file_name(file.filename[:-6])
        filename = file.filename
        upload_to = join(app.config['UPLOAD_FOLDER'], filename)

        if exists(upload_to):
            filename = '{}_{}.xmind'.format(filename[:-6], arrow.now().strftime('%Y%m%d_%H%M%S'))
            upload_to = join(app.config['UPLOAD_FOLDER'], filename)

        file.save(upload_to)
        insert_record(filename)
        g.is_success = True
        return filename

    elif file.filename == '':
        g.is_success = False
        g.error = "Please select a file!"

    else:
        g.is_success = False
        g.invalid_files.append(file.filename) 
Example 48
Source File: trac2down.py    From tracboat with GNU General Public License v3.0 6 votes vote down vote up
def save_file(text, name, version, date, author, path):
    # We need to create a directory structure matching the hierarchical
    # page title, e.g.:
    # name == 'Chapter1/Main'
    # the output file will be:
    # Chapter1/Main.md
    components = name.split("/")
    name = components[-1]
    levels = components[:-1]
    if levels:
        path = os.path.join(path, *levels)
        if not os.path.exists(path):
            os.makedirs(path)
    filename = os.path.join(path, name + '.md')
    with codecs.open(filename, 'w', encoding='utf-8') as fp:
        # print >>fp, '<!-- Name: %s -->' % name
        # print >>fp, '<!-- Version: %d -->' % version
        # print >>fp, '<!-- Last-Modified: %s -->' % date
        # print >>fp, '<!-- Author: %s -->' % author
        fp.write(text) 
Example 49
Source File: util.py    From spark-cluster-deployment with Apache License 2.0 6 votes vote down vote up
def saveAsLibSVMFile(data, dir):
        """
        Save labeled data in LIBSVM format.

        @param data: an RDD of LabeledPoint to be saved
        @param dir: directory to save the data

        >>> from tempfile import NamedTemporaryFile
        >>> from fileinput import input
        >>> from glob import glob
        >>> from pyspark.mllib.util import MLUtils
        >>> examples = [LabeledPoint(1.1, Vectors.sparse(3, [(0, 1.23), (2, 4.56)])), \
                        LabeledPoint(0.0, Vectors.dense([1.01, 2.02, 3.03]))]
        >>> tempFile = NamedTemporaryFile(delete=True)
        >>> tempFile.close()
        >>> MLUtils.saveAsLibSVMFile(sc.parallelize(examples), tempFile.name)
        >>> ''.join(sorted(input(glob(tempFile.name + "/part-0000*"))))
        '0.0 1:1.01 2:2.02 3:3.03\\n1.1 1:1.23 3:4.56\\n'
        """
        lines = data.map(lambda p: MLUtils._convert_labeled_point_to_libsvm(p))
        lines.saveAsTextFile(dir) 
Example 50
Source File: classification_results.py    From cleverhans with MIT License 6 votes vote down vote up
def save_to_file(self, filename, remap_dim0=None, remap_dim1=None):
    """Saves matrix to the file.

    Args:
      filename: name of the file where to save matrix
      remap_dim0: dictionary with mapping row indices to row names which should
        be saved to file. If none then indices will be used as names.
      remap_dim1: dictionary with mapping column indices to column names which
        should be saved to file. If none then indices will be used as names.
    """
    # rows - first index
    # columns - second index
    with open(filename, 'w') as fobj:
      columns = list(sorted(self._dim1))
      for col in columns:
        fobj.write(',')
        fobj.write(str(remap_dim1[col] if remap_dim1 else col))
      fobj.write('\n')
      for row in sorted(self._dim0):
        fobj.write(str(remap_dim0[row] if remap_dim0 else row))
        for col in columns:
          fobj.write(',')
          fobj.write(str(self[row, col]))
        fobj.write('\n') 
Example 51
Source File: code_editor.py    From equant with GNU General Public License v2.0 6 votes vote down vote up
def do_save_file(self, file, text, confirm):
        if confirm and file in self.__mdy_files and \
            QMessageBox.Cancel == QMessageBox.question(self, '提示', '该策略已被修改,是否保存?', QMessageBox.Ok | QMessageBox.Cancel):
            return

        try:
            with open(file, mode='w', encoding='utf-8') as f:
                f.write(text.replace('\r', ''))
        except Exception as e:
            print(e)    

        self.__mdy_files.remove(file)  

        if self.__save_mdy and not len(self.__mdy_files):
            self.__save_mdy = False
            self.on_saveMdySignal.emit() 
Example 52
Source File: sql.py    From spark-cluster-deployment with Apache License 2.0 6 votes vote down vote up
def saveAsParquetFile(self, path):
        """Save the contents as a Parquet file, preserving the schema.

        Files that are written out using this method can be read back in as
        a SchemaRDD using the L{SQLContext.parquetFile} method.

        >>> import tempfile, shutil
        >>> parquetFile = tempfile.mkdtemp()
        >>> shutil.rmtree(parquetFile)
        >>> srdd = sqlCtx.inferSchema(rdd)
        >>> srdd.saveAsParquetFile(parquetFile)
        >>> srdd2 = sqlCtx.parquetFile(parquetFile)
        >>> srdd2.collect() == srdd.collect()
        True
        """
        self._jschema_rdd.saveAsParquetFile(path) 
Example 53
Source File: labelImg.py    From LabelImgTool with MIT License 6 votes vote down vote up
def saveFile(self, _value=False):
        assert not self.image.isNull(), "cannot save empty image"
        if self.hasLabels():
            if self.defaultSaveDir is not None and len(
                    str(self.defaultSaveDir)):
                print 'handle the image:' + self.filename
                self._saveFile(self.filename)
            else:
                self._saveFile(self.filename if self.labelFile
                               else self.saveFileDialog())
        elif self.task_mode == 3:
            self._saveFile(self.filename)
        else:
            imgFileName = os.path.basename(self.filename)
            if self.task_mode in [0,1]:
                savedFileName = os.path.splitext(
                imgFileName)[0] + LabelFile.suffix
            elif self.task_mode in [2,3]:
                savedFileName = os.path.splitext(
                imgFileName)[0] + '.txt'
            savedPath = os.path.join(
            str(self.defaultSaveDir), savedFileName)
            if os.path.isfile(savedPath):
                os.remove(savedPath) 
Example 54
Source File: conf_check.py    From dne-dna-code with MIT License 6 votes vote down vote up
def save_config_to_ios_file(backup_config_ios_path, syslog=False):
    """Saves the current running configuration locally to the filesystem

    Args:
        backup_config_ios_path (str): IOS path to the backup configuration
        syslog (boolean): True, if informational messages should be sent to
            the syslog

    Returns:
        None
    """
    cli('copy running-config {}\n'.format(backup_config_ios_path))

    message = ('Running configuration was saved to {}'.format(
        backup_config_ios_path
    ))
    if syslog:
        send_syslog(message) 
Example 55
Source File: __init__.py    From CO2MPAS-TA with European Union Public License 1.1 6 votes vote down vote up
def save_output_file(output_file, output_file_name):
    """
    Save output file.

    :param output_file_name:
        Output file name.
    :type output_file_name: str

    :param output_file:
        Output file.
    :type output_file: io.BytesIO
    """
    output_file.seek(0)
    os.makedirs(osp.dirname(output_file_name), exist_ok=True)
    with open(output_file_name, 'wb') as f:
        f.write(output_file.read())
    log.info('CO2MPAS output written into (%s).', output_file_name) 
Example 56
Source File: audio_utilities.py    From griffin_lim with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def save_audio_to_file(x, sample_rate, outfile='out.wav'):
    """Save a mono signal to a file.

    Args:
        x (1-dim Numpy array): The audio signal to save. The signal values should be in the range [-1.0, 1.0].
        sample_rate (int): The sample rate of the signal, in Hz.
        outfile: Name of the file to save.

    """
    x_max = np.max(abs(x))
    assert x_max <= 1.0, 'Input audio value is out of range. Should be in the range [-1.0, 1.0].'
    x = x*32767.0
    data = array.array('h')
    for i in range(len(x)):
        cur_samp = int(round(x[i]))
        data.append(cur_samp)
    f = wave.open(outfile, 'w')
    f.setparams((1, 2, sample_rate, 0, "NONE", "Uncompressed"))
    f.writeframes(data.tostring())
    f.close() 
Example 57
Source File: base.py    From FastWordQuery with GNU General Public License v3.0 6 votes vote down vote up
def save_default_file(self, filepath_in_mdx, savepath=None):
        '''
        default save file interface
        '''
        basename = os.path.basename(filepath_in_mdx.replace('\\', os.path.sep))
        if savepath is None:
            savepath = '_' + basename
        if os.path.exists(savepath):
            return savepath
        try:
            src_fn = self.dict_path.replace(self._filename+u'.mdx', basename)
            if os.path.exists(src_fn):
                shutil.copy(src_fn, savepath)
                return savepath
            else:
                bytes_list = self.builder.mdd_lookup(filepath_in_mdx, ignorecase=config.ignore_mdx_wordcase)
                if bytes_list:
                    with open(savepath, 'wb') as f:
                        f.write(bytes_list[0])
                    return savepath
        except sqlite3.OperationalError as e:
            pass 
Example 58
Source File: data.py    From comet-commonsense with Apache License 2.0 6 votes vote down vote up
def save_eval_file(opt, stats, eval_type="losses", split="dev", ext="pickle"):
    if cfg.test_save:
        name = "{}/{}.{}".format(utils.make_name(
            opt, prefix="garbage/{}/".format(eval_type),
            is_dir=True, eval_=True), split, ext)
    else:
        name = "{}/{}.{}".format(utils.make_name(
            opt, prefix="results/{}/".format(eval_type),
            is_dir=True, eval_=True), split, ext)
    print("Saving {} {} to {}".format(split, eval_type, name))

    if ext == "pickle":
        with open(name, "wb") as f:
            pickle.dump(stats, f)
    elif ext == "txt":
        with open(name, "w") as f:
            f.write(stats)
    elif ext == "json":
        with open(name, "w") as f:
            json.dump(stats, f)
    else:
        raise