我正在编写一个 python 脚本来替换具有特定扩展名 (.seq) 的目录中每个文本文件中的字符串。替换的字符串只能来自每个文件的第二行,输出是一个新的子目录(称为 clean),其文件名与原始文件相同,但带有 *.clean 后缀。输出文件包含与原始文本完全相同的文本,但替换了字符串。我需要用“N”替换所有这些字符串:“K”、“Y”、“W”、“M”、“R”、“S”。
这是我在谷歌搜索后想到的。它非常混乱(编程的第二周),并且它停止在将文件复制到干净目录中而不替换任何内容。我真的很感激任何帮助。
先谢谢了!
import os, shutil
os.mkdir('clean')
for file in os.listdir(os.getcwd()):
if file.find('.seq') != -1:
shutil.copy(file, 'clean')
os.chdir('clean')
for subdir, dirs, files in os.walk(os.getcwd()):
for file in files:
f = open(file, 'r')
for line in f.read():
if line.__contains__('>'): #indicator for the first line. the first line always starts with '>'. It's a FASTA file, if you've worked with dna/protein before.
pass
else:
line.replace('M', 'N')
line.replace('K', 'N')
line.replace('Y', 'N')
line.replace('W', 'N')
line.replace('R', 'N')
line.replace('S', 'N')
一些注意事项:
-
string.replace
and re.sub
不是就位,因此您应该将返回值分配回您的变量。
-
glob.glob
更适合在目录中查找与定义模式匹配的文件...
- 也许您应该在创建目录之前检查该目录是否已经存在(我只是假设这一点,这可能不是您想要的行为)
- the
with
语句负责以安全的方式关闭文件。如果你不想使用它,你必须使用try
finally
.
- 在您的示例中,您忘记添加后缀
*.clean
;)
- 你实际上并没有编写文件,你可以像我在示例中那样做或者使用
fileinput
模块(直到今天我还不知道)
这是我的例子:
import re
import os
import glob
source_dir=os.getcwd()
target_dir="clean"
source_files = [fname for fname in glob.glob(os.path.join(source_dir,"*.seq"))]
# check if target directory exists... if not, create it.
if not os.path.exists(target_dir):
os.makedirs(target_dir)
for source_file in source_files:
target_file = os.path.join(target_dir,os.path.basename(source_file)+".clean")
with open(source_file,'r') as sfile:
with open(target_file,'w') as tfile:
lines = sfile.readlines()
# do the replacement in the second line.
# (remember that arrays are zero indexed)
lines[1]=re.sub("K|Y|W|M|R|S",'N',lines[1])
tfile.writelines(lines)
print "DONE"
希望能帮助到你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)