问题描述
我在文件夹和子文件夹中有文件。文件夹结构是这样的
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
我有文件名列表。
li = ['abc1','abc2','abc3','abc4']
i have list of file names.li = ['abc1','abc2','abc3','abc4']
我想知道这些文件是否存在于目录中。每个子目录应具有全部4个文件。否则,代码必须返回不存在特定文件的路径。
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在开放方法中很难给出路径。另请注意,我存储在文件夹中的文件名的末尾有日期,因此也需要在路径中解决该问题,以便对于文件名末尾的任何日期,如果文件夹中携带名称在列表中的文件,那么什么都不做,但是如果文件是子文件夹中丢失,然后打印EXCEPT文件不包含路径。
请注意,每个文件夹都必须包含所有4个文件(如果没有,则必须返回所有文件)。
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.
推荐答案
一种可能的方法:
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)
这篇关于文件是否存在,通过列表中匹配的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!