收集的幾個Python小技巧分享
獲得當前機器的名字:
def hostname():
sys = os.name
if sys == 'nt':
hostname = os.getenv('computername')
return hostname
elif sys == 'posix':
host = os.popen('echo $HOSTNAME')
try:
hostname = host.read()
return hostname
finally:
host.close()
else:
return 'Unkwon hostname'
獲取當前工作路徑:
import os
os.getcwd()
#or
#os.curdir just return . for current working directory.
#need abspath() to get full path.
os.path.abspath(os.curdir)
獲取系統(tǒng)的臨時目錄:
os.getenv('TEMP')
字符串與int,long,float的轉(zhuǎn)化:
python的變量看起來是沒有類型的,其實是有變量是有類型的。
使用locale模塊下的atoi和atof來將字符串轉(zhuǎn)化為int或float,或者也可以直接使用int(),float(),str()來轉(zhuǎn)化。以前的版本中atoi和atof是在string模塊下的。
s = "1233423423423423"
import locale
locale.atoi(s)
#1233423423423423
locale.atof(s)
#1233423423423423.0
int(s)
#1233423423423423
float(s)
#1233423423423423.0
str(123434)
"123434"
bytes和unicodestr的轉(zhuǎn)化:
# bytes object
b = b"example"
# str object
s = "example"
# str to bytes
bytes(s, encoding = "utf8")
# bytes to str
str(b, encoding = "utf-8")
# an alternative method
# str to bytes
str.encode(s)
# bytes to str
bytes.decode(b)
寫平臺獨立的代碼必須使用的:
>>> import os
>>> os.pathsep
';'
>>> os.sep
'\\'
>>> os.linesep
'\r\n'
相關文章
python中的selenium實現(xiàn)自動向下滾動頁面并指定最大滑動距離
這篇文章主要介紹了python中的selenium實現(xiàn)自動向下滾動頁面并指定最大滑動距離,下文有關selenium的資料介紹有一定的參考價值,需要的小伙伴可以參考一下2022-02-02Python通用驗證碼識別OCR庫ddddocr的安裝使用教程
dddd_ocr是一個用于識別驗證碼的開源庫,又名帶帶弟弟ocr,下面這篇文章主要給大家介紹了關于Python通用驗證碼識別OCR庫ddddocr的安裝使用教程,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07Iconfont(矢量圖標)+iconmoon(圖標svg互轉(zhuǎn))配合javascript實現(xiàn)社交分享系統(tǒng)
這篇文章主要介紹了Iconfont(矢量圖標)+iconmoon(圖標svg互轉(zhuǎn))配合javascript實現(xiàn)社交分享系統(tǒng),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04python優(yōu)雅實現(xiàn)代碼與敏感信息分離的方法
這篇文章主要介紹了python優(yōu)雅實現(xiàn)代碼與敏感信息分離的方法,在flask中,python-dotenv 可以無縫接入項目中,只要你的項目中存在 .env 或者 .flaskenv 文件,他就會提示你是否安裝 python-dotenv,需要的朋友可以參考下2022-05-05Python辦公自動化之發(fā)送電子郵件和Outlook集成
Python辦公?動化是利?Python編程語?來創(chuàng)建腳本和程序,以簡化、加速和?動化?常辦公任務和?作流程的過程,本文主要介紹一下如何利用Python實現(xiàn)發(fā)送電子郵件和Outlook集成,需要的可以參考下2023-12-12