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?
2 Answers
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.
Comments
Just pipe the output of ls (filtering the files you want) into stdin of xargs:
❯❯❯ ls *.txt | xargs -I{} python3 file.py {} 1 Comment
tripleee
No, don't use
ls. The shell already expands *.txt before ls even runs. There is no need for xargs then either.
.txtextension?