0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
LoganLee
  • 145
  • 1
  • 10

4 Answers4

1

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}"])
ken
  • 1,543
  • 1
  • 2
  • 14
1

Seems likes file path was missing the working directory part. Also using tail makes things a bit less difficult

#!/usr/bin/env python3
import os
import subprocess

CWD = os.getcwd()
files = [f for f in os.listdir(CWD) if str(f).endswith(".fasta")]
subprocess.run(["tail", "-n", "+1", *files])

cat is probably not the best tool to use in this case. But if you really want to use cat, then I would suggest to do it like this:

for f in files:
    file_path = CWD+"/"+f
    subprocess.run(["echo", f])
    subprocess.run(["cat", file_path])

I might be wrong, but it doesn't really makes a lot of sense to call bash from python, when it can be done within python as well.

seq = ""
files = [f for f in os.listdir(CWD) if str(f).endswith(".fasta")]
for f in files:
    seq += ">" + f + "\n"
    fasta = open(f'{CWD}/{f}', "r")
    seq += fasta.read()
    fasta.close()
out = open("A_B.fasta", "w")
out.write(seq)
out.close()
carassius
  • 26
  • 3
0

I am uncertain why you'd want to exec a new command (cat) to do this when you can use Python's built-in file operations to do it instead.

Append a text to file in Python

James McPherson
  • 2,476
  • 1
  • 12
  • 16
-3

I saw this post: https://www.delftstack.com/howto/python/python-cat/

import os

os.system("echo 'Hello! Python is the best programming language.' >> ~/file.txt")
os.system("cat ~/file.txt")

Output: Hello! Python is the best programming language.

Dharman
  • 30,962
  • 25
  • 85
  • 135