下面是我的目录的一个示例:
> SSSRRR2.bam SSSRRR24.bam
>
> SSSRRR2.bam.bai SSSRRR24.bam.bai
>
> SSSRRR2.split.bam SSSRRR24.split.bam
>
> SSSRRR2.ump.fastq SSSRRR24.ump.fastq我需要的唯一文件是每个ID的.split.bam和.bam文件,以便应用subprocess.check_output。这是我编写的python脚本:
#!/usr/bin/env python
import os
import subprocess
if __name__=='__main__':
path = os.getcwd()
dir_files = os.listdir(path)
pair_reads = {}
for file in sorted(dir_files):
if file.endswith(".split.bam"):
ID_1 = file.split(".")[0]
file1 = file
if file.endswith(".bam") and not file.endswith(".split.bam") and not file.endswith(".bam.bai"):
ID_2 = file.split(".")[0]
file2 = file
if ID_1 == ID_2:
pair_reads[file1] = file2
for key, value in pair_reads.items():
# print(key)
name = key.split(".")[0]
subprocess.check_output("tepid-discover -k -d -i --strict -D -p 36 -n " + name + " -c " + key + " s " + value, shell = True)然而,当我应用循环时,我的问题是缩进。如果if的每个块是相互独立的,那么如何将连接引入到这两个块,例如在这个块中:
if ID_1 == ID_2:
pair_reads[file1] = file2这就是我遇到的错误:
if ID_1 == ID_2:
NameError: name 'ID_1' is not defined另外,我使用的是python2,因为该程序与python2一起工作。
提前谢谢你的帮助。我希望我说得很清楚。
发布于 2020-01-08 01:11:14
在循环的一次迭代中,只能定义一个ID_1和ID_2,因为它一次只查看一个文件,这两个条件是相互排斥的。
这个问题有两个简单的解决方法:您可以给出ID_1和ID_2默认值,或者在检查它们是否相同之前添加另一个条件(例如,“如果定义了两个ID并且它们是相同的”)。
但是,这可能无法使您的程序工作,因为os.listdir可能以与您预期不同的顺序列出文件。
最简单的解决方案可能是只查看.split.bam文件或.bam文件,然后自己构建另一个文件。
import os
for file in os.listdir(path):
# separate the last two file extensions from the base name
basename, *extensions = file.rsplit(os.extsep, 2)
if extensions == ['split', 'bam'] and basename:
# found basename.split.bam
bamfile = basename + '.bam'
if os.path.exists(bamfile):
# use basename, bamfile, and file however you want
subprocess.check_output(...)这将查找每个.split.bam文件,并在运行最后一行之前检查对应的.bam文件是否存在。
发布于 2020-01-08 00:28:26
这似乎与缩进没有任何关系。您的程序不会运行第一个if语句。我不知道你想做什么,但是你可以把这个比较嵌套在
try:
ID_1 and ID_2
except:
print("qwe")https://stackoverflow.com/questions/59637808
复制相似问题