我正在编写一个python脚本来替换具有特定扩展名(.seq)的目录中的每个文本文件中的字符串。替换的字符串应该只来自每个文件的第二行,并且输出是一个新的子目录(称之为干净),其文件名与原始文件相同,但带有* .clean后缀。输出文件包含与原始文本完全相同的文本,但替换了字符串。我需要替换所有这些字符串:'K','Y','W','M','R','S'和'N'。
这是我在谷歌搜索后想出来的。这是非常混乱的(编程的第二周),它停止将文件复制到干净的目录而不替换任何东西。我真的很感激任何帮助。
先谢谢!
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')
答案 0 :(得分:7)
一些注意事项:
string.replace
和re.sub
不在原位,因此您应该将返回值分配回您的变量。glob.glob
更适合在匹配定义模式的目录中查找文件... 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"
希望它有所帮助。
答案 1 :(得分:5)
您应该将line.replace('M', 'N')
替换为line=line.replace('M', 'N')
。 replace返回原始字符串的副本,并替换相关的子字符串。
更好的方法(IMO)是使用re。
import re
line="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
line=re.sub("K|Y|W|M|R|S",'N',line)
print line
答案 2 :(得分:4)
您需要将替换结果分配回“line”变量
line=line.replace('M', 'N')
您还可以使用模块fileinput进行就地编辑
import os, shutil,fileinput
if not os.path.exists('clean'):
os.mkdir('clean')
for file in os.listdir("."):
if file.endswith(".seq"):
shutil.copy(file, 'clean')
os.chdir('clean')
for subdir, dirs, files in os.walk("."):
for file in files:
f = fileinput.FileInput(file,inplace=0)
for n,line in enumerate(f):
if line.lstrip().startswith('>'):
pass
elif n==1: #replace 2nd line
for repl in ["M","K","Y","W","R","S"]:
line=line.replace(ch, 'N')
print line.rstrip()
f.close()
将inplace = 0更改为inplace = 1,以便对文件进行现场编辑。
答案 3 :(得分:4)
以下是一些一般性提示:
请勿使用find
来检查文件扩展名(例如,这也会匹配“file1.seqdata.xls
”)。至少使用file.endswith('seq')
,或者更好的是os.path.splitext(file)[1]
实际上,不要完全这样做。这就是你想要的:
import glob
seq_files = glob.glob("*.seq")
不要复制文件,只使用一个循环要容易得多:
for filename in seq_files:
in_file = open(filename)
out_file = open(os.path.join("clean", filename), "w")
# now read lines from in_file and write lines to out_file
请勿使用line.__contains__('>')
。你的意思是
if '>' in line:
(将在内部调用__contains__
)。但实际上,你想知道开始这一行是用“”>“,而不是在行内的某个地方,不管是在开头还是没有。所以更好的方法是:
if line.startswith(">"):
我不熟悉你的文件类型;如果">"
检查确实仅用于确定第一行,那么有更好的方法可以做到这一点。
您不需要if
块(仅pass
)。写作更清晰
if not something:
do_things()
other_stuff()
而不是
if something:
pass
else:
do_things()
other_stuff()
学习Python很有趣!
答案 4 :(得分:0)
line.replace不是mutator,它保持原始字符串不变,并返回一个带有替换的新字符串。您需要将代码更改为line = line.replace('R', 'N')
等。
我认为您还希望在else子句的末尾添加break
语句,这样您就不会遍历整个文件,而是在处理第2行后停止。
最后,您需要实际编写包含更改的文件。到目前为止,您只是在读取文件并更新程序变量“line”中的行。您还需要实际创建一个输出文件,您将在其中编写修改后的行。