CARLOSLEO280
CARLOSLEO280

Reputation: 81

how can i select specific text files using glob2 library

i have been working on this code and i wanted to know what would i need to do if there is a way to select specific files instead of all of the files with the same extension

import glob2
from datetime import datetime



filenames = glob2.glob("*.txt")
with open(datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")+".txt", 'w') as file:
    for filename in filenames:
        with open(str(filename), "r") as f:
            file.write(f.read() + "\n")

i have tried getting the specific files in a tuple or list and it wouldn't work

Upvotes: 2

Views: 408

Answers (1)

RoadRunner
RoadRunner

Reputation: 26315

You can try storing your text files in and checking if the files from filenames exist in it:

import glob2

files = {'file1.txt', 'file2.txt'} # can use list or tuple here also

filenames = glob2.glob("*.txt")
for file in filenames:
    if file in files:
        # Do something with file

Alternatively, you could just use os.listidr(), since you only want specific files:

from os import listdir

files = {'file1.txt', 'file2.txt'}

for file in listdir('.'):
    if file in files:
        # Do something with file

Upvotes: 1

Related Questions