dub
dub

Reputation: 21

How open file based on extension?

I want to open any .txt file in the same directory.

In ruby I can do

File.open("*.txt").each do |line|
       puts line
end

In python I can't do this it will give an error

file = open("*.txt","r")
print(file.read())
file.close()

It gives an error invalid argument.

So is there any way around it?

Upvotes: 0

Views: 1125

Answers (2)

pulkit-singhal
pulkit-singhal

Reputation: 847

You can directly use the glob module for this

import glob
for file in glob.glob('*.txt'):
    with open(file, 'r') as f:
        print(f.read())

Upvotes: 5

zvone
zvone

Reputation: 19382

Use os.listdir to list all files in the current directory.

all_files = os.listdir()

Then, filter the ones which have the extension you are looking for and open each one of them in a loop.

for filename in all_files:
    if filename.lower().endswith('.txt'):
        with open(filename, 'rt') as f:
            f.read()

Upvotes: 1

Related Questions