Problem reading text files without extensions in python

I wrote a piece of code that should read texts inside several files that are in a directory. These files are mostly text files, but they do not have any extensions. But my code cannot read them:

corpus_path = 'Reviews/'

for infile in glob.glob(os.path.join(corpus_path,'*.*')):
    review_file = open(infile,'r').read()
    print review_file

To check if this code works, I put a dummy text file dummy.txt. which worked because it has an extension. But I do not know what to do so that files without extensions can be read. Can anybody help me? Thanks

+3
source share
4 answers

Just use *instead *.*.

The latter requires an extension (more precisely, there must be a period in the file name), the first not.

+5
source

Glob , Windows. * *.*. .. os.path.join(corpus_path,'*'). , * - , , .

. glob module.

+6

You can search *instead *.*, but this will match every file in your directory.

Basically, this means that you will have to handle cases where the file you are opening is not a text file.

+3
source

it seems that you need

from os import listdir

from filename in ( fn for fn in listdir(corpus_path) if '.' not in fn):
    # do something

you could write

from os import listdir

for fn in listdir(corpus_path):
    if '.' not in fn:
        # do something

but the first with the generator retains one level of indentation

0
source

Source: https://habr.com/ru/post/1790433/


All Articles