收集的几个Python小技巧分享

yipeiwu_com6年前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)

获取系统的临时目录:

复制代码 代码如下:

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'

相关文章

python3 selenium自动化 frame表单嵌套的切换方法

python3 selenium自动化 frame表单嵌套的切换方法

在web自动化测试中,测试工程师经常会碰到frame表单嵌套结构,直接定位会报错,我们需要切换表单后才能成功定位。 我拿QQ邮箱登录来作为例子说下frame怎么切换。 qq邮箱页面按F...

对Python中list的倒序索引和切片实例讲解

Python中list的倒序索引和切片是非常常见和方便的操作,但由于是倒序,有时候也不太好理解或者容易搞混。 >>> nums = [0, 1, 2, 3, 4,...

Python程序设计入门(4)模块和包

Python语言功能非常强大,除了类之外,还有模块和包的概念,这有点像perl,此处简单说说包和模块。 一、Python中的模块 模块——其实就是我们说的库(lib)的概念,不过它不仅只...

python跳过第一行快速读取文件内容的实例

Python编程时,经常需要跳过第一行读取文件内容。简单的做法是为每行设置一个line_num,然后判断line_num是否为1,如果不等于1,则进行读取操作。 相应的Python代码如...

Python3实现的字典、列表和json对象互转功能示例

本文实例讲述了Python3实现的字典、列表和json对象互转功能。分享给大家供大家参考,具体如下: python3可以使用json模块操作json json.dumps(): 对jso...