[关闭]
@breakerthb 2017-06-07T05:28:41.000000Z 字数 1293 阅读 1345

Python常用方法

Python


main函数的写法

if __name__=="__main__":
    print(abc)

查看方法库位置

import sys; 
sys.path

添加寻找库的目录

import sys
sys.path.append("../Lib")

查看数据类型

type(a)

Python代码文件发布

目录操作

1.查看当前目录

import os
os.getcwd()

2.切换当前目录

os.chdir('....')

文件操作

1.打开文件

file = open('sketch.txt')

file = open('sketch.txt', 'w')

2.关闭文件

file.close()

3.读取文件

content = file.readline()
print(content)

4.写文件

file.write('XXXX')

5.跳转

seek(0) # 参数为行号

6.逐行打印

file.seek(0) 
for line in file: 
    print(line)

7.判断文件是否存在

if os.path.exists('sketch.txt'):
file = open('sketch.txt')

PS:

在python3中,可以通过pickle模块进行数据的序列化保存。

字符串处理

ref:http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html

1.字符串分割

# abc : XXXXXX
(a, b) = line.split(":")
print(a)
print(b)

如果有的行存在多个分号:

(a, b) = line.split(":", 1)

如果有的行不存在分号:

2.找到固定字符的位置

pos = line.find(':') # 返回-1表示没找到

3.过滤掉前后多余空格

b = b.strip()

4.字符串替换

a = 'hello word'

word替换为python

1 replace方法

a.replace('word','python')

2 正则表达式

import re
strinfo = re.compile('word')
b = strinfo.sub('python',a)
print b

异常处理

file = open('sketch.txt')

try:
    for line in file:
        (a, b) = line.split(':', 1)
        print(a)
        print(b)
except:
    pass

finally:
    file.close()

另外:

try:
    with open('out.txt', "w") as fileOut:
        for item in man:
            fileOut.write(item)
except:
    print("output error")

用with打开文件可以不用考虑关闭

排序

data.sort()
data1 = sorted(data)

反向排序

data.sort().reverse()

或者按顺序从尾部pop()

pop() #读出并删除末尾元素

去重

集合中的元素会自动忽略掉重复的。

data = [a, b, c, a]
data1 = set(data)

推到列表

把一个列表中的所有数据按照一定规则处理之后生成一个新的列表

字典

相当于结构体或map

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注