-1

So I have a python file file.py. And I have a directory that has many .txt file. So I was wondering how do I do python3 file.py txt1.txt, python3 file.py txt2.txt and so on for every txt file in the directory?

John Sean
  • 37
  • 6

2 Answers2

1

Here is the alternative solution using find:

find /path/to/your/txtfiles/*.txt -type f -exec python3 file.py {} \;

I like find because I think it makes it easier to recursively search through directories while matching specific conditions.

Here -type f is selecting only regular files, and -exec is running your script with the filename being substituted in place of the curly braces.

terafl0ps
  • 684
  • 5
  • 8
-1

Just pipe the output of ls (filtering the files you want) into stdin of xargs:

❯❯❯ ls *.txt | xargs -I{} python3 file.py {}
Abhishek Jaisingh
  • 1,614
  • 1
  • 13
  • 23
  • No, [don't use `ls`](https://mywiki.wooledge.org/ParsingLs). The shell already expands `*.txt` before `ls` even runs. There is no need for `xargs` then either. – tripleee Apr 03 '20 at 04:04