Python学习使用记录
Tags: script
-
将python中的打印消息输出到log文件
#将控制台输出覆盖写入到文件 python myprint.py > myprint.txt #将控制台输出追加写入到文件 python myprint.py >> myprint.txt
-
检查字符串是否是以指定子字符串开头
str.startswith(str, beg=0,end=len(string));
-
将外部excel或文件作为参数传递进来
xls = sys.argv[1] #parameter list for external input,【1】indicate the second parameter
-
字典中的元素本无序,可用以下让字典中的元素为顺序为输入的先后顺序
int_dict = collections.OrderedDict()
-
format 函数使用,格式化打印字符串 format 函数可以接受不限个参数,位置可以不按顺序
“{} {}”.format(“hello”, “world”) # 不设置指定位置,按默认顺序
‘hello world’“{0} {1}”.format(“hello”, “world”) # 设置指定位置
‘hello world’“{1} {0} {1}”.format(“hello”, “world”) # 设置指定位置
‘world hello world’ -
if的判断语句可灵活运用
-
异常处理 try…exception,可用在为别人提供一些公共使用脚本,并打印出消息报告。
try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。如果你不想在异常发生时结束你的程序,只需在try里捕获它。
try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") except IOError: print "Error: 没有找到文件或读取文件失败" else: print "内容写入文件成功" fh.close()
以上程序输出结果:
$ python test.py 内容写入文件成功 $ cat testfile # 查看写入的内容 这是一个测试文件,用于测试异常!!
-
python 中logging(日志)使用
-
python os 常用介绍
os 模块提供了非常丰富的方法用来处理文件和目录。
[os.getcwd()](https://www.runoob.com/python/os-getcwd.html) 返回当前工作目录 os.open(file, flags[, mode]) 打开一个文件,并且设置需要的打开选项,mode参数是可选的 os.write(fd, str) 写入字符串到文件描述符 fd中. 返回实际写入的字符串长度
-
name
#!/usr/bin/python3 # Filename: using_name.py if __name__ == '__main__': print('程序自身在运行') else: print('我来自另一模块')
一个模块被另一个程序第一次引入时,其主程序将运行。如果我们想在模块被引入时,模块中的某一程序块不执行,我们可以用__name__属性来使该程序块仅在该模块自身运行时执行。
-
random 常用方法
import random print( random.randint(1,10) ) # 产生 1 到 10 的一个整数型随机数 print( random.random() ) # 产生 0 到 1 之间的随机浮点数 print( random.uniform(1.1,5.4) ) # 产生 1.1 到 5.4 之间的随机浮点数,区间可以不是整数 print( random.choice('tomorrow') ) # 从序列中随机选取一个元素 print( random.randrange(1,100,2) ) # 生成从1到100的间隔为2的随机整数 a=[1,3,5,6,7] # 将序列a中的元素顺序打乱 random.shuffle(a) print(a)
-
excel 数据处理
-
os.rmdir()——删除指定目录
-
os.mkdir()——创建目录注意:这样只能建立一层,
-
os.makedirs()——递归建立目录