当前位置: 首页>>代码示例>>Python>>正文


Python utils.write_file函数代码示例

本文整理汇总了Python中utils.write_file函数的典型用法代码示例。如果您正苦于以下问题:Python write_file函数的具体用法?Python write_file怎么用?Python write_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了write_file函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: indexWiki

def indexWiki():
	utils.write_file("wiki/index.html", 'Index <br/>')
	l=glob.glob("corpus/*")
	l.sort()
	for path in l:
		i=path[7:]
		utils.add_file("wiki/index.html", '<li><a href="'+i+'.html">'+i+'</a></li>')
开发者ID:petosorus,项目名称:wikileaks,代码行数:7,代码来源:graphe.py

示例2: genereHtml

def genereHtml(d, i):
	s = utils.read_file("corpus/" + i)
	for j in d[i]:
		pattern = re.compile(j + ' ' , re.I)
		s = pattern.sub('<a href="keywords/' + j + '.html"/>' + j + "</a> ", s)
		# print j, "\n", s.encode('utf-8'), "\n\n"
	utils.write_file("wiki/" + i + ".html", s)
开发者ID:petosorus,项目名称:wikileaks,代码行数:7,代码来源:graphe.py

示例3: save_items_as_text

    def save_items_as_text(self, event):
        """Export current selection as CSV file."""
        if hasattr(self, 'toRename'):
            CSVfile = ""
            q = app.prefs.get('logEnclose')
            sep = app.prefs.get('logSeparator')
            ext = app.prefs.get('logFextension')

            if app.showTimes:
                t = time.time()

            # create file contents
            for original, renamed in self.toRename:
                CSVfile += unicode(q + original[0] + q + sep + q + renamed[0] + q + '\n')

            if app.showTimes:
                print("Export file contents for %s items: %s" % (len(self.toRename), (time.time() - t)))

            # triggered by menu, allow to choose output file
            if event:
                dlg = wx.FileDialog(self, message=_(u"Save current items as ..."),
                                    defaultDir='', defaultFile=u'.%s' % ext,
                                    wildcard=_(u"CSV file (*.%s)") % ext + u'|*.%s' % ext,
                                    style=wx.SAVE | wx.OVERWRITE_PROMPT
                                    )
                if dlg.ShowModal() == wx.ID_OK:
                    # attempt to write file
                    utils.write_file(dlg.GetPath(), CSVfile)
                dlg.Destroy()
            # auto logging, generate file name
            else:
                file = time.strftime("undo_%Y-%m-%d_%Hh%Mm%Ss",
                                     time.localtime()) + '.' + app.prefs.get('logFextension')
                path = os.path.join(app.prefs.get(u'logLocation'), file)
                utils.write_file(path, CSVfile)
开发者ID:jgrinder,项目名称:metamorphose2,代码行数:35,代码来源:__init__.py

示例4: available_models

def available_models(experiments, variables, frequencies, realms, cmor_tables, outfile=None):
    """Get a list of models with the required data.

    Args:
        experiments (list): list of experiments required
        variables (list): list of variables required
        frequencies (list): list of time frequency
        realms (list): CMIP5 realm
        cmor_tables (list): CMOR table
        outfile (Optional[str]): full file path to optionally write out data

    Returns:
        set

    """
    models = []
    iterator = itertools.product(experiments, variables, frequencies, realms, cmor_tables)
    for experiment, variable, frequency, realm, cmor_table in iterator:
        files = availability("*", experiment, frequency, realm, cmor_table, "r1i1p1", variable)
        models.append([f.split("/")[7] for f in files])

    # Get the common models in the lists of lists
    result = set(models[0])
    for item in models[1:]:
        result.intersection_update(item)

    # Optionally write the file
    if outfile != None:
        utils.write_file(sorted(result), outfile)

    return sorted(result)
开发者ID:ajferraro,项目名称:jazz,代码行数:31,代码来源:cmip5.py

示例5: main

def main():
    parser = argparse.ArgumentParser(description = 'Exporting data matrix from HIT summary result.')
    parser.add_argument('-f', action = 'append', help = 'The CSV files.')
    parser.add_argument('-c', help = 'The exporting columns separated with comma.')
    parser.add_argument('-o', help = 'The output file.')
    parser.add_argument('-t', help = 'The types used to filter out data row.')
    parser.add_argument('-p', default = '0', help = 'The padding for filtered rows.')
    parser.add_argument('-d', help = 'The data source file.')

    args = parser.parse_args()

    data_sources = []
    data_labels = []
    data_ids = []
    if (args.d != None):
        data_sources = utils.load_file(args.d)

        data_metainfo = regex_datasource(data_sources)

        # data_labels: flickr high interesting 1, flickr low interesting 2, pinterest [3, 4, 5]
        data_labels = data_metainfo[0]
        # data_ids: (flickr, pinterest) image id
        data_ids = data_metainfo[1]

    output = read_data(args, data_sources, data_labels)

    if (args.o != None):
        utils.write_file(output, args.o)
开发者ID:viirya,项目名称:flickr_fetcher,代码行数:28,代码来源:export_datamatrix_from_summary.py

示例6: post

 def post(self, request, app_name, env_name, app_path):
     action = request.data['action']
     if action == 'rename':
         env_path = _get_existent_env_path(app_path, env_name)
         new_env_name = request.data['name']
         check_name(new_env_name)
         new_env_path = _get_absent_env_path(app_path, new_env_name)
         stop_patsaks(get_id(request.dev_name, app_name, env_name))
         write_file(new_env_path, new_env_name)
         schema_prefix = get_id(request.dev_name, app_name) + ':'
         execute_sql(
             'SELECT ak.rename_schema(%s, %s)',
             (schema_prefix + env_name.lower(),
              schema_prefix + new_env_name.lower()))
         os.remove(env_path)
         return HttpResponse()
     if action == 'eval':
         request.lock.release()
         request.lock = None
         if env_name == _RELEASE_ENV_NAME:
             env_name = None
         response = send_to_ecilop(
             'EVAL ' + get_id(request.dev_name, app_name, env_name),
             request.data['expr'])
         assert response
         status = response[0]
         result = response[1:]
         assert status in ('E', 'F', 'S')
         if status == 'E':
             raise Error(result, status=NOT_FOUND)
         return {'ok': status == 'S', 'result': result}
     raise Error('Unknown action: "%s"' % action)
开发者ID:akshell,项目名称:chatlanian,代码行数:32,代码来源:app_handlers.py

示例7: dockerfile_to_singularity

def dockerfile_to_singularity(dockerfile_path, output_dir=None):
    '''dockerfile_to_singularity will return a Singularity build file based on
    a provided Dockerfile. If output directory is not specified, the string
    will be returned. Otherwise, a file called Singularity will be written to 
    output_dir
    :param dockerfile_path: the path to the Dockerfile
    :param output_dir: the output directory to write the Singularity file to
    '''
    if os.path.basename(dockerfile_path) == "Dockerfile":
        spec = read_file(dockerfile_path)
        # Use a common mapping
        mapping = get_mapping()
   
        # Put into dict of keys (section titles) and list of commands (values)
        sections = organize_sections(lines=spec,
                                     mapping=mapping)

        # We have to, by default, add the Docker bootstrap
        sections["bootstrap"] = ["docker"]

        # Put into one string based on "order" variable in mapping
        build_file = print_sections(sections=sections,
                                    mapping=mapping)
        if output_dir != None:
            write_file("%s/Singularity" %(output_dir),build_file)
            print("Singularity spec written to %s" %(output_dir))
        return build_file

    # If we make it here, something didn't work
    logger.error("Could not find %s, exiting.", dockerfile_path)
    return sys.exit(1)
开发者ID:gmkurtzer,项目名称:singularity,代码行数:31,代码来源:converter.py

示例8: test_ifnonematch

    def test_ifnonematch(self):

        file1contents = "file 1 contents"
        utils.write_file("file.txt", file1contents)

        response = self.client.request("GET", "/file.txt")
        (status, reason, body, headers) = response

        etag = utils.get_header("etag", headers)

        headers = {"If-None-Match": etag}
        response = self.client.request("GET", "/file.txt", headers)
        (status, reason, body, headers) = response
        
        self.assertEqual(status, 304)                

        file1contents = "file 1 contents - even more!"
        utils.write_file("file.txt", file1contents)

        headers = {"If-None-Match": etag}
        response = self.client.request("GET", "/file.txt", headers)
        (status, reason, body, headers) = response

        self.assertEqual(status, 200)
        self.assertEquals(file1contents, body)
开发者ID:pmuellr,项目名称:slowebs,代码行数:25,代码来源:test_read.py

示例9: write_address

def write_address(csvfile):
    PREFECTURE = 6
    CITY = 7
    TOWN = 8

    address_set = set()
    with open(csvfile, newline="", encoding="shift_jis") as cf:
        rows = csv.reader(cf, delimiter=",")
        for row in rows:
            address = "".join([row[PREFECTURE], row[CITY]])
            town = row[TOWN]
            if town == "以下に掲載がない場合":
                continue
            else:
                sections = town.split("、")
                for s in sections:
                    house_number_index = s.find("(")
                    if house_number_index > -1:
                        s = s[:house_number_index]
                    address_set.add((address, s))

    dataset = []
    for p, t in address_set:
        dataset.append((p, t))

    utils.write_file(ADDRESS_TXT, dataset)
开发者ID:SnowMasaya,项目名称:Watson_Hackthon_Disaster_Day2,代码行数:26,代码来源:address.py

示例10: test_write_read_files

    def test_write_read_files(self):
        '''test_write_read_files will test the functions write_file and read_file
        '''
        print("Testing utils.write_file...")
        from utils import write_file
        import json
        tmpfile = tempfile.mkstemp()[1]
        os.remove(tmpfile)
        write_file(tmpfile,"hello!")
        self.assertTrue(os.path.exists(tmpfile))        

        print("Testing utils.read_file...")
        from utils import read_file
        content = read_file(tmpfile)[0]
        self.assertEqual("hello!",content)

        from utils import write_json
        print("Testing utils.write_json...")
        print("Case 1: Providing bad json")
        bad_json = {"Wakkawakkawakka'}":[{True},"2",3]}
        tmpfile = tempfile.mkstemp()[1]
        os.remove(tmpfile)        
        with self.assertRaises(TypeError) as cm:
            write_json(bad_json,tmpfile)

        print("Case 2: Providing good json")        
        good_json = {"Wakkawakkawakka":[True,"2",3]}
        tmpfile = tempfile.mkstemp()[1]
        os.remove(tmpfile)
        write_json(good_json,tmpfile)
        content = json.load(open(tmpfile,'r'))
        self.assertTrue(isinstance(content,dict))
        self.assertTrue("Wakkawakkawakka" in content)
开发者ID:gmkurtzer,项目名称:singularity,代码行数:33,代码来源:test_client.py

示例11: print_all_hits

def print_all_hits(all_hits, filename, sep = ',', field_index = 0, with_header = True):

    output = []

    count = 0
    for hit in all_hits[0]:

        (first_hit, first_hit_row, org_first_hit) = reformat_hit(hit, sep, 0)

        for hits in all_hits[1:len(all_hits)]:
            for hit in hits[0:len(hits)]:
                (hit, hit_row, org_hit) = reformat_hit(hit, sep, 0)
                
                if (first_hit[4] == hit[4]):
                    (hit, hit_row, org_hit) = reformat_hit(org_hit, sep)

                    if (field_index != 0):
                        (first_hit, first_hit_row, org_first_hit) = reformat_hit(org_first_hit, sep, field_index)

                    if (first_hit[len(first_hit) - 1] == ''):
                        first_hit_row += hit_row
                    else:
                        first_hit_row += sep + hit_row

        if (count == 0 and with_header == False):
            count += 1
            continue

        output.append(first_hit_row)

    if (filename != None):
        utils.write_file(output, filename)

    return output
开发者ID:viirya,项目名称:flickr_fetcher,代码行数:34,代码来源:join_hitresults.py

示例12: print_hit_with_data_labels

def print_hit_with_data_labels(hits, data_labels, filename):


    output = []

    print("data label: #" + str(len(data_labels)))

    labels = ', '.join(data_labels)

    print(labels)

    output.append(labels)

    for hit in hits:
        org_hit = hit
        hit = hit.rsplit(',')
        if (len(hit) <= 1):
            hit = org_hit.rsplit("\t")
        hit = hit[8:len(hit)]
        print("hit row: #" + str(len(hit)))
        hit_row = ', '.join(hit)
        print(hit_row)
        output.append(hit_row)

    if (filename != None):
        utils.write_file(output, filename)
开发者ID:viirya,项目名称:flickr_fetcher,代码行数:26,代码来源:analyze_hitresult.py

示例13: test_get_existing_links

 def test_get_existing_links(self):
     """Test get_existing_links()"""
     with utils.TempDir() as tmpdir:
         utils.write_file(os.path.join(tmpdir, 'orig'), 'foo')
         os.symlink('orig', os.path.join(tmpdir, 'lnk'))
         self.assertEqual(python_tools.get_existing_links(tmpdir),
                          [os.path.join(tmpdir, 'lnk')])
开发者ID:salilab,项目名称:developer_tools,代码行数:7,代码来源:test_python_tools.py

示例14: main

def main():
    if request.method == 'GET':
        return render_template('enter_name_or_code.html')

    # get args
    company_name = request.form.get('c_name')
    ticker = request.form.get('c_ticker')

    if not company_name and not ticker:
        flash('Введите название или тикер')
        return redirect(url_for('main'))

    # if ticker is not provided, find it by name.
    # If not successful, flash error and redirect
    if not ticker:
        t, msg = find_single_ticker(company_name)
        if not t:
            flash(msg)
            return redirect(url_for('main'))
        ticker = t

    # get date and lag args
    deal_date = request.form.get('deal_date')
    future_lag = int(request.form.get('future_lag'))
    past_lag = int(request.form.get('past_lag'))

    # validate existence
    if not deal_date or not future_lag or not past_lag:
        flash('Введите дату, лаг вперед и лаг назад.')
        return redirect(url_for('main'))

    # validate date format
    try:
        deal_date = datetime.strptime(deal_date, '%d.%m.%Y')
    except ValueError:
        flash('Некорректный формат даты.')
        return redirect(url_for('main'))

    # validate weekdays
    if deal_date.weekday() in [5, 6]:
        msg = '{} - выходной день. В этот день не было торгов. Выберите рабочий день.'
        flash(msg.format(deal_date.strftime('%d.%m.%Y')))
        return redirect(url_for('main'))

    hist_data = get_historical_data(ticker, deal_date, future_lag, past_lag)

    # get_historical_data() will return '404' if the request is unsuccessful
    # i.e. wrong ticker specified
    if hist_data == '404':
        flash('Такого тикера не существует.')
        return redirect(url_for('main'))

    if not company_name:
        company_name = ticker
    filename = ticker + '.xls'
    write_file(hist_data, deal_date, company_name, filename)

    return send_file(filename,
                     as_attachment=True,
                     attachment_filename=filename)
开发者ID:kurtgn,项目名称:tamara-stocks,代码行数:60,代码来源:app.py

示例15: build_pages

def build_pages(config):
    """
    Builds all the pages and writes them into the build directory.
    """
    site_navigation = nav.SiteNavigation(config['pages'], config['use_direcory_urls'])
    loader = jinja2.FileSystemLoader(config['theme_dir'])
    env = jinja2.Environment(loader=loader, trim_blocks=True)

    for page in site_navigation.walk_pages():
        # Read the input file
        input_path = os.path.join(config['docs_dir'], page.input_path)
        input_content = open(input_path, 'r').read().decode('utf-8')

        # Process the markdown text
        html_content, table_of_contents, meta = convert_markdown(input_content)
        html_content = post_process_html(html_content, site_navigation)

        context = get_context(
            page, html_content, site_navigation,
            table_of_contents, meta, config
        )

        # Allow 'template:' override in md source files.
        if 'template' in meta:
            template = env.get_template(meta['template'][0])
        else:
            template = env.get_template('base.html')

        # Render the template.
        output_content = template.render(context)

        # Write the output file.
        output_path = os.path.join(config['site_dir'], page.output_path)
        utils.write_file(output_content.encode('utf-8'), output_path)
开发者ID:OlderWoo,项目名称:hiloteam.github.io,代码行数:34,代码来源:build.py


注:本文中的utils.write_file函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。