0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
dub
  • 21
  • 1
  • 9
  • You would have to find all files that end with .txt in that directory, and then have a for loop that reads the file. Here is a way to grab only files with certain extensions in a directory: https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python – jeremysprofile May 31 '18 at 19:50
  • You'll have to do it yourself. Take a look at os.listdir() – Treyten Carey May 31 '18 at 19:50

2 Answers2

5

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())
pulkit-singhal
  • 845
  • 5
  • 15
1

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()
zvone
  • 18,045
  • 3
  • 49
  • 77
  • Thanks, i used this way before but i found it bit inefficient – dub May 31 '18 at 19:58
  • @yippiez Inefficient as spends too much CPU, too much memory, or too much of your time as a developer? If it is the last one, well, create a function which you will always call ;) – zvone May 31 '18 at 20:02