简体   繁体   English

Python:如何在特定条件下读取目录中的所有文件?

[英]Python : How to read all files in the directory with some specific condition?

I want to read all the files in one directory. 我想读取一个目录中的所有文件。 Directory contains following files: 目录包含以下文件:

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

When I'm running my script I want to give this file name on the console in the format as : ABC11. 当我运行脚本时,我想在控制台上以以下格式提供此文件名: ABC11。

After that I want to read all the files with only ABC11 extensions in the sorted order. 之后,我想按排序顺序读取仅具有ABC11扩展名的所有文件。 ie first ABC11_1.csv,ABC11_2.csv,ABC11_3.csv like that. 即像这样的第一个ABC11_1.csv,ABC11_2.csv,ABC11_3.csv。

If user gives only ABC application must have to give error message. 如果用户仅给出ABC应用程序,则必须给出错误消息。 If user gives only ABC1 then it is valid application accept this and check in the directory for files with the extension ABC1, if available then process the files in sorted order,if not then error message. 如果用户仅提供ABC1,则它是有效的应用程序,接受该请求并在目录中检查扩展名为ABC1的文件,如果可用,则按排序顺序处理文件,如果没有,则显示错误消息。

Program-Code- 程序代码

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 LineName 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)

I'm doing like that and it work's fine for me but is that other best ways to do this stuff. 我正在那样做,对我来说很好,但是其他最好的方式可以做到这一点。 Please provide all your responses? 请提供您的所有回复?

Thanks. 谢谢。

According to your question, following pseudo code should work 根据您的问题,以下伪代码应该可以工作

import os 

# Read all files from a directory, and read your input argument
files = os.listdir("your_input_directory_path")
input_argument = "ABC11"

# Sort file names by name
files = sorted(files) 

relevant_files = []
for file_name in files:
    # Your Conditions goes here ........

    if file_name.startswith(input_argument):
        relevant_files.append(file_name)



if relevant_files:
    return "Error | Not Found"
else:
    return relevant_files

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM