Home > other >  Use glob to match files without a file extension
Use glob to match files without a file extension

Time:06-07

I am trying to use glob to match all the files in a folder. All the files start with the same word but I forgot to include .txt at the end of them. Is there a way to write the code to get all of these files despite the fact there is no file extension in my directory?

CodePudding user response:

I'm assuming you want to add a .txt file extension from the way you worded your question. You can use a wildcard character (*) anywhere in your glob expression

import glob
import shutil

for file in glob.glob('/path/to/files/commonWord*'):
    shutil.move(file, file   '.txt')

CodePudding user response:

not sure if that is what you want, but this will get all the files/folders that start with the word "california" in the same directory.

So if no folders start with "california" in your directory this will do it

import glob, os

for file_ in glob.glob('california*'):
    os.rename(file_, file_ '.csv')

output1: ['california_housing_train', 'california_housing_test']

output2: ['california_housing_train.csv', 'california_housing_test.csv']

CodePudding user response:

You can take them all and then check by regex whether or not it has an extension and add the file to a list or whatever you want.

import glob
import re

files = glob.glob('*')

for file in files:
    if not re.findall(r'.*\.[a-z] ',file):
        print(file)
  • Related