Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中使用glob模式读取目录中的文件?_Python_File_Directory_Glob - Fatal编程技术网

如何在python中使用glob模式读取目录中的文件?

如何在python中使用glob模式读取目录中的文件?,python,file,directory,glob,Python,File,Directory,Glob,我想在一个目录中读取文件 目录包含: ABC1.csv ABC1_1.csv ABC1_2.csv ABC11.csv ABC11_1.csv ABC11_3.csv ABC11_2.csv ABC13_4.csv ABC13_1.csv ABC17_6.csv ABC17_2.csv ABC17_4.csv ABC17_8.csv #if input is ABC1 .\\ABC1.csv .\\ABC1_1.csv .\\ABC1_2.csv #if input is ABC11 .\\A

我想在一个目录中读取文件

目录包含:

ABC1.csv
ABC1_1.csv
ABC1_2.csv
ABC11.csv
ABC11_1.csv
ABC11_3.csv
ABC11_2.csv
ABC13_4.csv
ABC13_1.csv
ABC17_6.csv
ABC17_2.csv
ABC17_4.csv
ABC17_8.csv
#if input is ABC1
.\\ABC1.csv
.\\ABC1_1.csv
.\\ABC1_2.csv
#if input is ABC11
.\\ABC11.csv
.\\ABC11_1.csv
.\\ABC11_2.csv
.\\ABC11_3.csv
运行脚本时,我想根据某些条件给出读取特定文件的命令行参数:

  • 如果用户只给出ABC错误消息
  • 如果用户给出ABC1,则必须仅读取ABC1.csv、ABC1_1.csv和ABC1_2.csv
  • 如果用户给出ABC11,则必须仅读取ABC11.csv、ABC11_1.csv、ABC11_2.csv、ABC11_3.csv
  • 如果用户提供ABC13,则必须仅读取ABC13_1.csv、ABC13_4.csv
  • 如果用户给出ABC17,则必须仅读取ABC17_2.csv、ABC17_4.csv、ABC17_6.csv、ABC17_8.csv
  • 对于这些东西,我创建了一个脚本,但我面临着一个问题

    节目-

    from glob import glob
    import os
    import sys
    
    file_pattern = ''
    files_list = list()
    arguments = {'ABC', 'PQR', 'XYZ'}
    
    if len(sys.argv[1:2]) is 1:
       file_pattern = str(sys.argv[1:2])
    else:   
       print 'run as <python test.py ABC>'
       sys.exit(1)
    if file_pattern in arguments:
       print '<Provide Name with some Number>'
       sys.exit(1)
    
    file_pattern = file_pattern.replace('[','').replace(']','').replace('\'','')
    
    if file_pattern.startswith('ABC',0,3):
       files_list = glob(os.path.join('<directory name>', str(file_pattern)+'_*.csv'))
    else:
       print 'No Such File --> ' + str(file_pattern)+ '\t  <Provide appropriate Name>'
       sys.exit(1)
    
    if files_list:
       for a_file in sorted(files_list):
          print a_file
          #process file
    else:
       print 'No Such File --> ' + str(file_pattern)+ '\t  <Provide appropriate Name>'
       sys.exit(1)
    
    从全局导入全局
    导入操作系统
    导入系统
    文件模式=“”
    文件列表=列表()
    参数={'ABC','PQR','XYZ'}
    如果len(sys.argv[1:2])为1:
    file_pattern=str(sys.argv[1:2])
    其他:
    打印“运行方式”
    系统出口(1)
    如果参数中的文件类型为:
    打印“
    系统出口(1)
    file\u pattern=file\u pattern.replace('[','').replace(']','').replace('\'','')
    如果文件\u pattern.startswith('ABC',0,3):
    files\u list=glob(os.path.join(“”,str(file\u模式)+“”*.csv'))
    其他:
    打印“没有这样的文件-->”+str(文件模式)+'\t”
    系统出口(1)
    如果文件列表:
    对于排序中的文件(文件列表):
    打印文件
    #进程文件
    其他:
    打印“没有这样的文件-->”+str(文件模式)+'\t”
    系统出口(1)
    
    此代码工作正常,但不满足我的第二个条件。当用户将ABC1作为参数(即python test.py ABC1)时,它将返回文件ABC1_1.csv、ABC1_2.csv,但不返回ABC1.csv文件


    如何在不丢失任何其他条件的情况下满足第二个条件?

    我有一个解决方案。这不是完美的,取决于文件夹中是否有其他文件:

    file_pattern = 'ABC1'
    files_list = glob(os.path.join('<directory name>', str(file_pattern)+'[!0-9]*'))
    # output: ABC1.csv, ABC1_1.csv, ABC1_2.csv
    
    file_pattern = 'ABC11'
    files_list = glob(os.path.join('<directory name>', str(file_pattern)+'[!0-9]*'))
    # output: ['.\\ABC11.csv', '.\\ABC11_1.csv', '.\\ABC11_2.csv', '.\\ABC11_3.csv']
    
    文件模式='ABC1'
    files_list=glob(os.path.join(“”,str(file_模式)+'[!0-9]*'))
    #输出:ABC1.csv、ABC1_1.csv、ABC1_2.csv
    文件模式='ABC11'
    files_list=glob(os.path.join(“”,str(file_模式)+'[!0-9]*'))
    #输出:['.\\ABC11.csv','.\\ABC11\u 1.csv','.\\ABC11\u 2.csv','.\\ABC11\u 3.csv']
    
    我和杰斯珀有同样的问题。问题是,虽然*将匹配任何字符,但它需要一个字符


    通过选择任何在文件模式后没有数字的文件,我们避免了1-11问题。

    我尝试了不同的场景,最终得到了满足我所有条件的精确解决方案。首先,我检查用户输入文件是否在指定的目录中可用,如果可用,则将所有文件与相同的文件进行全局处理,最后将匹配文件附加到相同的列表中

    如果用户输入If not file在指定的目录中不可用,则我将检查带有(u)符号的文件,然后将所有文件全局化到列表中。最后对列表进行迭代,得到最终结果

    节目-

    from glob import glob
    import os
    import sys
    
    file_pattern = ''
    files_list = list()
    
    arguments = {'ABC', 'PQR', 'XYZ'}
    
    #checking for user provided argument or not
    if len(sys.argv[1:2]) is 1:
       file_pattern = str(sys.argv[1:2])
    else:   
       print 'run as < python test.py <LineName> >'
       sys.exit(1)
    #replace all unnecessary stuff with ('')
    file_pattern = file_pattern.replace('[','').replace(']','').replace('\'','')
    
    #checking for line number is provided or not
    if file_pattern in arguments:
       print '<Provide LineName with some Number>'
       sys.exit(1)
    
    flag = True
    #list of all files containing specified directory
    files = os.listdir('<directory name>')
    
    for file_name in files:
       if str(file_name) == str(file_pattern)+'.csv':
          files_list = glob(os.path.join('<directory name>', str(file_pattern)+'_*.csv'))
          #appending match file also to resultant list
          files_list.append('<directory name>'+file_name)
          flag = False
    #if specified file is not present in dir check for filename with (_)
    if flag:
       files_list = glob(os.path.join('<directory name>', str(file_pattern)+'_*.csv'))
    
    #checking for list contains items or not
    if files_list:
       for a_file in sorted(files_list):
          print a_file
    else:
       print 'No Such File --> ' + str(file_pattern)+ '\t  <Provide appropriate Name1>'
       sys.exit(1)
    

    您可能希望为附加的“特殊”情况添加一个简单检查,如下所示:

    if file_pattern.startswith('ABC',0,3):
       csv_path = os.path.join('.', str(file_pattern))
       files_list = glob(csv_path + '_*.csv')
       # Just check the special case that's not included in the glob above
       csv_path = csv_path + '.csv'
       if os.path.isfile(csv_path):
          files_list.append(csv_path)
    else:
       print 'No Such File --> ' + str(file_pattern)+ '\t  <Provide appropriate Name>'
       sys.exit(1)
    
    if file_pattern.startswith('ABC',0,3):
    csv_path=os.path.join('.',str(文件模式))
    文件列表=全局(csv路径+'.*.csv')
    #只需检查上面的glob中未包含的特殊情况
    csv_路径=csv_路径+'.csv'
    如果os.path.isfile(csv\u路径):
    文件\u列表.append(csv\u路径)
    其他:
    打印“没有这样的文件-->”+str(文件模式)+'\t”
    系统出口(1)
    
    我想说,像test.py ABC1这样的调用不会像预期的那样返回ABC11.csv,而是返回ABC1_*.csv。但是,与您的问题文本相反,它不会返回ABC1.csv。示例代码的版本是否符合问题?@Jesper Freesbug-是的,对。。。如果我们删除(u),那么它将返回ABC1.csv、ABC11.csv、ABC11_1.csv以及所有以ABC1开头的内容。但我想清楚地解释的是,如果你有任何建议,请给出?@dodell-是的,这是不正确的。“我想满足我所有的条件。”多德尔-得到了正确的解决方案。请看我的答案。