Search code examples
pythonlinuxsubprocesscat

How to use linux command "cat" from a script?


Input:A.fasta

>A
sldkfjslkdcskd

Input:B.fasta

>B
pofnvkweu

Expected output:A_B.fasta

>A
sldkfjslkdcskd
>B
pofnvkweu

Code:

my_model_dir_path='../my_model'
word='.fasta'

for f in os.listdir(my_model_dir_path):
    if word in f:
        subprocess.call(["cat", f"{f}"])

Error message:

No such file or directory

I used subprocess to call linux command cat to concatenate fasta files in a fasta format like expected output. However, I got a message like No such file or directory even though the files and the directory exist in right path.


Solution

  • os.listdir returns a path relative to the given directory. So, you are try to cat a file at ./A.fasta instead of ../my_model/A.fasta.

    Try this:

    for f in os.listdir(my_model_dir_path):
        if word in f:
            subprocess.call(["cat", f"{my_model_dir_path}/{f}"])
    

    If you are using python3, pathlib is useful.

    from pathlib import Path
    
    for f in Path(my_model_dir_path).glob("*.fasta"):
        subprocess.call(["cat", f"{f}"])