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?
Asked
Active
Viewed 137 times
-1

John Sean
- 37
- 6
-
are you trying to read every file with `.txt` extension? – Apr 02 '20 at 21:22
-
@midrizi yes! that is correct – John Sean Apr 02 '20 at 21:32
2 Answers
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