Sushmita Pal
Sushmita Pal

Reputation: 23

Opening a list of files and executing a script

I wanted to list all the .pdb files and .ent files and execute the script and prints the sequence but it seems the program is not running properly and it does not show me any result.The code is

    import os
    path="c:/pdb"
    dirs=os.listdir(path)
    for file in dirs:
        list1=[]
        for lines in file:
            list=lines.split()
            id=list[0]
            if id=='ATOM' or id=='HETATM':
                if list[4]=='A':
                    if list[2]=='C4':
                        list1.append(list[3])
         print("The sequence is:" ,list1)

Upvotes: 0

Views: 45

Answers (2)

cs95
cs95

Reputation: 403278

Working on windows, you can try specifying your path with an escaped backslash.

import os
path = "c:\\pdb"
for file in os.listdir(path):
    list1 = []
    for lines in open(file):
        list = lines.split()
        idl = list[0]
        if (idl == 'ATOM' or idl == 'HETATM') and list[4]=='A' and list[2]=='C4':
            list1.append(list[3])

    print("The sequence is:", list1)

Also, the ifs have been collapsed but they do the same thing. Overly deep indentations can hinder readability.

Upvotes: 1

Bogusław Kałka
Bogusław Kałka

Reputation: 84

os.listdir return a list of strings [1] so you can't do "for lines in file" on them (doing that, you just iterates over file name string, not over file contents). You can use os.walk() [2] for this, e.g.:

import os
path = 'c:/pdb'
for dirpath, dirnames, fnames in os.walk(path):
    for fname in fnames:
        if fname.endswith('txt'):
            with open(os.path.join(dirpath, fname)) as fp:
                for line in fp:
                    <program logic here>

Also remember not to use reserved words like "list" or "id" - check those here docs.python.org/3.3/reference/lexical_analysis.html#keywords

[1] https://docs.python.org/3/library/os.html#os.listdir

[2] https://docs.python.org/3/library/os.html#os.walk

Upvotes: 0

Related Questions