獲得當前機器的名字:
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)
獲取系統的臨時目錄:
os.getenv('TEMP')
字符串與int,long,float的轉化:
python的變量看起來是沒有類型的,其實是有變量是有類型的。
使用locale模塊下的atoi和atof來將字符串轉化為int或float,或者也可以直接使用int(),float(),str()來轉化。以前的版本中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的轉化:
# 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'
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
