Python Examples of pathlib.Path.joinpath - ProgramCreek.com

文章推薦指數: 80 %
投票人數:10人

The following are 5 code examples for showing how to use pathlib.Path.joinpath(). These examples are extracted from open source projects. You can vote up the ... SearchbyModuleSearchbyWordProjectSearchTopPythonAPIsPopularProjectsJavaC++PythonScalaBlogreportthisadMorefrompathlib.Path.cwd().home().joinpath().resolve().is_file().exists().mkdir().expanduser()reportthisadRelatedMethodsos.path.join()sys.path()os.path.abspath()time.time()unittest.TestCase()time.sleep()os.remove()os.makedirs()random.random()uuid.uuid4()getpass.getpass()functools.wraps()setuptools.find_packages()requests.Session()matplotlib.pyplot.show()matplotlib.pyplot.title()matplotlib.pyplot.ylabel()matplotlib.pyplot.xlabel()matplotlib.pyplot.plot()configparser.ConfigParser()RelatedModulesossysretimeloggingrandommathsubprocessshutiljsonnumpycollectionsfunctoolsargparsepathlibPythonpathlib.Path.joinpath()ExamplesThefollowingare5 codeexamplesforshowinghowtousepathlib.Path.joinpath(). Theseexamplesareextractedfromopensourceprojects. Youcanvoteuptheonesyoulikeorvotedowntheonesyoudon'tlike, andgototheoriginalprojectorsourcefilebyfollowingthelinksaboveeachexample.YoumaycheckouttherelatedAPIusageonthesidebar.Youmayalsowanttocheckoutallavailablefunctions/classesofthemodule pathlib.Path ,ortrythesearchfunction .Example1Project: robin_stocks   Author:jmfernandes   File:export.py   License:MITLicense6 votes defcreate_absolute_csv(dir_path,file_name,order_type): """Createsafilepathgivenadirectoryandfilename. :paramdir_path:Absoluteorrelativepathtothedirectorythefilewillbewritten. :typedir_path:str :paramfile_name:Anoptionalargumentforthenameofthefile.Ifnotdefined,filenamewillbestock_orders_{currentdate} :typefile_name:str :paramfile_name:Willbe'stock','option',or'crypto' :typefile_name:str :returns:Anabsolutefilepathasastring. """ path=Path(dir_path) directory=path.resolve() ifnotfile_name: file_name="{}_orders_{}.csv".format(order_type,date.today().strftime('%b-%d-%Y')) else: file_name=fix_file_extension(file_name) return(Path.joinpath(directory,file_name))Example2Project: TSDK   Author:xinlingqudongX   File:SDK基类.py   License:MITLicense6 votes defconsole(self,log_options:dict={}): '''日志输出设置 日志的输出格式为:行号时间级别::路径->文件名->函数名=>消息 日志添加两个:一个是文本日志记录,一个用于控制台输出 ''' log_config=OrderedDict({ 'level':logging.ERROR, 'filename':'', 'datefmt':'%Y-%m-%d%H:%M:%S', 'filemode':'a', 'format':'%(lineno)d%(asctime)s@%(levelname)s::%(pathname)s->%(filename)s->%(funcName)s=>%(message)s' }) log_config.update(log_options)iflog_optionselseNone logging.basicConfig(**log_config) file_log=logging.FileHandler(Path.joinpath(Path.cwd(),f'{Path(__file__).name.split(".")[0]}-log.txt')) console_log=logging.StreamHandler() console_log.setLevel(logging.DEBUG) logger=logging.getLogger(__name__) logger.addHandler(file_log) logger.addHandler(console_log)Example3Project: pypyr-cli   Author:pypyr   File:pipeline_runner.py   License:ApacheLicense2.05 votes defassert_pipeline_notify_match_file(pipeline_name, expected_notify_output_path): """AssertthatthepipelinehastheexpectedoutputtoNOTIFYlog. Args: pipeline_name:str.Nameofpipelinetorun.Relativeto./tests/ expected_notify_output_path:path-like.Pathtotextfilecontaining expectedoutput.Relativetoworkingdir. """ assert_pipeline_notify_output_is( pipeline_name, read_file_to_list(Path.joinpath(working_dir, 'pipelines', expected_notify_output_path)))Example4Project: intent_classifier   Author:deepmipt   File:multiclass.py   License:ApacheLicense2.05 votes defsave(self,fname=None): """ Methodsavestheintent_modelparametersinto<>_opt.json(or<>_opt.json) andintent_modelweightsinto<>.h5(or<>.h5) Args: fname:file_pathtosaveintent_model.Ifnotexplicitlygivenseld.opt["model_file"]willbeused Returns: nothing """ fname=self.model_path_.nameiffnameisNoneelsefname opt_fname=str(fname)+'_opt.json' weights_fname=str(fname)+'.h5' opt_path=Path.joinpath(self.model_path_,opt_fname) weights_path=Path.joinpath(self.model_path_,weights_fname) Path(opt_path).parent.mkdir(parents=True,exist_ok=True) #print("[savingintent_model:{}]".format(str(opt_path))) Path(opt_path).parent.mkdir(parents=True,exist_ok=True) self.model.save_weights(weights_path) withopen(opt_path,'w')asoutfile: json.dump(self.opt,outfile) returnTrueExample5Project: NeMo   Author:NVIDIA   File:helpers.py   License:ApacheLicense2.04 votes defmaybe_download_from_cloud(url,filename,subfolder=None,cache_dir=None,referesh_cache=False)->str: """ Helperfunctiontodownloadpre-trainedweightsfromthecloud Args: url:(str)URLofstorage filename:(str)whattodownload.Therequestwillbeissuedtourl/filename subfolder:(str)subfolderwithincache_dir.Thefilewillbestoredincache_dir/subfolder.Subfoldercan beempty cache_dir:(str)acachedirectorywheretodownload.Ifnotpresent,thisfunctionwillattempttocreateit. IfNone(default),thenitwillbe$HOME/.cache/torch/NeMo referesh_cache:(bool)ifTrueandcachedfileispresent,itwilldeleteitandre-fetch Returns: Ifsuccessful-absolutelocalpathtothedownloadedfile else-emptystring """ #try: ifcache_dirisNone: cache_location=Path.joinpath(Path.home(),'.cache/torch/NeMo') else: cache_location=cache_dir ifsubfolderisnotNone: destination=Path.joinpath(cache_location,subfolder) else: destination=cache_location ifnotos.path.exists(destination): os.makedirs(destination,exist_ok=True) destination_file=Path.joinpath(destination,filename) ifos.path.exists(destination_file): logging.info(f"Foundexistingobject{destination_file}.") ifreferesh_cache: logging.info("Askedtorefreshthecache.") logging.info(f"Deletingfile:{destination_file}") os.remove(destination_file) else: logging.info(f"Re-usingfilefrom:{destination_file}") returnstr(destination_file) #downloadfile wget_uri=url+filename logging.info(f"Downloadingfrom:{wget_uri}to{str(destination_file)}") wget.download(wget_uri,str(destination_file)) ifos.path.exists(destination_file): returndestination_file else: return""reportthisadAboutPrivacyContact



請為這篇文章評分?