-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?

2
  • are you trying to read every file with .txt extension? Commented Apr 2, 2020 at 21:22
  • @midrizi yes! that is correct Commented Apr 2, 2020 at 21:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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

❯❯❯ ls *.txt | xargs -I{} python3 file.py {} 

1 Comment

No, don't use ls. The shell already expands *.txt before ls even runs. There is no need for xargs then either.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.