问题
i have files in folders and subfolders. folder structure is like this
2020(folder)
-01(sub folder)
--14(sub-sub folder)
----abc1-2020-01-14.csv
----abc2-2020-01-14.csv
-02(subfolder in 2020)
--17(sub-sub folder in 02)
----abc1-2020-02-17.csv
----abc4-2020-02-17.csv
i have list of file names. li = ['abc1','abc2','abc3','abc4']
i want to know if these file exists in directory or not. each subdirectory should have all 4 files. if not then code must return path where particular file doesnot exist.
import glob
BASE_PATH = r'2020/'
allin= BASE_PATH + '/*/*'
li = ['abc1','abc2','abc3','abc4']
print('Names of files:')
for name in glob.glob(allin):
print('\t', name)
for k in li:
try:
f = open(r"C:\\Users\\Karar\\ProjectFiles\\scripts\\"+ name + "\\" + k + "*.csv")
except IOError:
print(name+k+ ".csv""File not present")
print name is returning 2020\01\14 and 2020\02\17
iam having difficulty in giving path here in open method. please also note that my filename stored in folders has date in the end so need to tackle that as well in path so that for any date at the end of file name if folder carry files with name in list then okay do nothing but if files are missing in sub folders then print EXCEPT file not present with path. note each folder has to carry all 4 files if not then return except.
回答1:
One possible approach:
import glob, os.path
base = '2020'
li = ['abc1','abc2','abc3','abc4']
for dirname in glob.glob(base + '/*/*'):
year, month, day = dirname.split('/')
for prefix in li:
filename = "{}/{}.csv".format(dirname, '-'.join(prefix, year, month, day))
if not os.path.exists(filename):
print(filename)
来源:https://stackoverflow.com/questions/60889174/file-exists-or-not-through-matching-filename-in-list