system.file.fileExists

I have a script which uses the system.file.fileExists function.
I have it working when I am looking for a specific csv file but I now want to change it so it checks for a csv file where I do not know the name of the file, only that the extension is a csv file.

The existing code I have that works is:

filepath = 'C:\\Recipe In\\BT{}\\WG10-CSV.csv'.format(furnace_brass_tag_num)
   	logger.info(filepath)
   	if system.file.fileExists(filepath):

I tried changing the code to:

filepath = 'C:\\Recipe In\\BT{}\\*.csv'.format(furnace_brass_tag_num)
		logger.info(filepath)
		if system.file.fileExists(filepath):

It isn’t working. How can I change this to work? All I need it to do is find any file in the folder with a .csv file extension

1 Like

fileExists won’t work for your purposes, but glob may:
https://docs.python.org/2.7/library/glob.html

Thanks. That function does return the file name along with the string.

I created a button running a script and have the results going to a custom value just for testing:

It returns the following correctly:

image

In reality I am only going to have one file in this folder that is a csv file.

Two questions now:

  1. I want to create a function or logic which will run and return the filename above. How would I get only the file name and not the actual entire path?

  2. Is there a way I can run this script in a function and not only return the filename only but also a true/false which I can then use to determine what to do if there is a file versus if there is not? Or would I not need the true/false part but just return the filename and if the filename returns an empty dataset I know there is no file?

For the first part, you can use os.path. For the second part, you can use the iter function to safely retrieve the first element of the list (or None if it’s empty):

import glob
from os.path import basename

path = "C:/Users/pgriffith/Downloads/"

csv = next(iter(glob.glob(path + "*.csv")), None)
if csv is not None:
	print basename(csv)
else:
	pass

Thanks! I ended up using the following:

	import glob
	
	furnace_brass_tag_num = self.view.params.BrassTagNum
	filepath = 'C:\\Recipe In\\BT{}\\*.csv'.format(furnace_brass_tag_num)
	file = glob.glob(filepath)
	self.view.custom.File = file
	
	if len(file)==0:
		self.view.custom.FileExists = 'No File'
	else:	
		self.view.custom.FileExists = 'File Found'

I checked the length of the list ‘file’ to determine if it was empty or not. Then I can use this to determine what to next if there is a file or not. Thanks for your help!