Home > Blockchain >  Search if filename with matching 4 digits exists in a directory
Search if filename with matching 4 digits exists in a directory

Time:10-26

I am checking if filename - 'Dev Finance GRM CONS ASPAC_Sales_3069_WI2_2020_GrsSalesAdj_Manual Upload Planning_1000records.csv' exists in a path

I am generating multiple files in the same path with similar name, but a unique pin ('3069') in the above case. This '3069' is stored in a unique variable 'upload_pin'

upload_pin = 3069 (and I want to search if a .csv file including this upload_pin exists in my path)

Tried this:

path = r"\\OPCITSNAPADCON2.jnj.com\tm1\cons\grm_aspac\user_in\Manual Upload Current Plan\Archive"
csv_files = glob.glob(os.path(path   '/*.csv'))
for filename in csv_files:
    if upload_pin in filename:
               print(filename)

CodePudding user response:

This worked for me

import os

upload_pin = 3069
for filename in os.listdir():
    if filename.endswith(".csv") and filename.find(str(upload_pin))>=0:
        print(filename)
    

CodePudding user response:

Try

# get file names of all csv files in the directory
os.chdir('...')
all_csv_files = glob.glob("*.csv")

# provide your pin
upload_pin = 3069

# for each one of your files
# if the file name contains the target pin, print the file name
for file in all_csv_files:
    if (str(upload_pin) in file):
        print(file)
  • Related