在写python脚本的时候可以套用模板+一些处理的语句例子更快的写好程序,因此想到来写这样的文章来与大家分享,有不足之处欢迎大家指出~
首先放上我最常用的几个模板:
模板一
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date : 2020-03-13
# Author : Myshu
# Mail : myshu0601@qq.com
# Version : 1.0
from __future__ import print_function
import getopt
import sys
import time
try:
from Bio import AlignIO, SeqIO
except ImportError:
sys.stderr.write("Error! BioPython is not detected!\n")
sys.exit(1)
def usage():
print ( 'Usage: \n'\
' -h | --help help \n' \
' -i input old bms.info\n' \
' -n input new bms.info\n' \
' -t tags file dir\n' \
' -o output final bms.info\n'\
'')
oldbms = ''
newbms = ''
tags_dir = ''
outputfile = ''
try:
opts, args = getopt.getopt(sys.argv[1:], "hi:n:t:o:", ["help"])
except getopt.GetoptError:
print ('getopt error!')
usage()
sys.exit(1)
for opt,arg in opts:
if opt in ('-h','--help'):
usage()
sys.exit(1)
elif opt in ('-i'):
oldbms = arg
elif opt in ('-n'):
newbms = arg
elif opt in ('-t'):
tags_dir = arg
elif opt in ('-o'):
outputfile = arg
# check the args
if oldbms=='':
print('ERROR: There must be a oldbms file!')
usage()
sys.exit(1)
if newbms=='':
print('ERROR: There must be a newbms file!')
usage()
sys.exit(1)
if tags_dir=='':
print('ERROR: There must be a tags_dir!')
usage()
sys.exit(1)
if outputfile=='':
print('ERROR: There must be a outputfile!')
usage()
sys.exit(1)
#------ def --------------------
# 打印当前时间的函数 2020-03-12 15:26:58
def PrintTime():
now = int(round(time.time() * 1000))
time_now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now / 1000))
# 设置输出字体为浅蓝色,调色可以参照链接:https://www.cnblogs.com/fangbei/p/python-print-color.html
time_now = "\033[0;36;40m" + time_now + "\033[0m"
return time_now
#------ main -------------------
print(PrintTime())
模板二
#!/usr/bin/env python3
"""
Usage: python3 <script> <conf_file> <tags.list> <out_dir> <merge_prefix>
"""
import subprocess
import sys
import os.path
from util import get_config
from BioUtil import xzopen, fastaFile
if len(sys.argv) != 5:
sys.exit(__doc__)
conf_file, taglist, out_dir, prefix = sys.argv[1:5]
# 传递参数,将参数存入字典
conf = get_config(conf_file, 'Module')
tag_num = int(conf['Number'])
我比较喜欢模板一,因为格式比较规范~
有了模板之后,就可以根据具体的处理方法对文件进行处理了,这里我根据自己平时写代码时候的习惯,收集了一些不同的处理语句(要注意语句中的变量需要自己调整
),打算之后不断更新:
1、文件读写
文件句柄:'r' 、'w'、'a'(追加)、'+'(可读可写)、'b'(二进制形式)、'v'(替换为\n)
# -------------- 1. 读取文件 --------------
# 1). 使用for语句
for line in open("Test_file.txt"):
print line, ## 去掉每行自身的换行符
print line.strip() ## 去掉每行自身的换行符
# 2). 使用with文件句柄
with open(inputfile) as f:
seqs = SeqIO.parse(f, "fasta")
for seq in seqs:
seq.id
seq.seq
len(seq)
samps = ((seq.name, seq.seq) for seq in sample(list(seqs),number))
for samp in samps:
print(">{}\n{}".format(*samp), file=output)
output.close() ##文件操作完成后必须关闭文件句柄
# 3). 读取打包gz文件
import gzip
from Bio import SeqIO
with gzip.open("test.fasta.gz", "rt") as handle:
for record in SeqIO.parse(handle, "fasta"):
print(record.id)
# -------------- 2. 读取文件夹 --------------
# read tags dir : <old name> => <tag dir>
dirs = os.listdir(tags_dir)
OldTags={}
for tags in dirs:
searchObj = re.search(r'^(.*).fa.gz$',tags)
if (searchObj):
# print(searchObj.group())
OldTags[searchObj.group(1)] = tags_dir + "/" + tags
# -------------- 3. 写入文件 --------------
output = open(outputfile, "w")
output.writelines(str.list) #将字符串列表写入文件
output.write(str) #把一个字符串写入文件
2、提取文件名或后缀
file = os.path.basename(outputfile)
dirname = os.path.dirname(outputfile)
name, ext = os.path.splitext(file)
# name C:/test_txt
# ext .png
3、判断文件夹/文件是否存在
import os
# 判断文件夹是否存在,不存在则创建,存在则删除再创建
if not os.path.exists(out_tags_dir):
os.makedirs(out_tags_dir)
else:
shutil.rmtree(out_tags_dir)
os.makedirs(out_tags_dir)
# 判断文件是否存在,存在则删除
if os.path.exists(Pathbms[Name]):
os.remove(Pathbms[Name])
4、正则匹配和替换
# 判断当前行开头是否为‘#’
if (line.startswith('#')):
print line
# 判断字符串中是否有子字符串
if '.' in name:
print("No '.' in Names!")
exit(0)
# 字符替换
name = name.replace(".","_")
#去除空行
import re
for line in open(file):
if re.match('^\s*$', line):
continue
5、去除字符串空白
"···xyz···".strip() # returns "xyz"
"···xyz···".lstrip() # returns "xyz···"
"···xyz···".rstrip() # returns "···xyz"
"··x·y·z··".replace(' ', '') # returns "xyz"
6、不断循环
# 不建议使用递归函数进行循环,因为递归函数会导致栈溢出
# 不管运行是否报错均可执行,可以加入break,自动停止,否则会一直运行下去
while True:
try:
x = int(input('Please enter a number: '))
#break
except Exception:
print('That was no valid number.')
7、读取shell脚本,并获取返回值
cmd = f"grep \"TotalReads \" {fq1_data_path}/*.report|awk 'NR==1{{a=$2*4/40000000;print int(a)==(a)?int(a):int(a)+1}}'"
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
file_num = stdout.decode("utf-8")
file_num = int(file_num.strip())
print(file_num)
网友评论