簡體   English   中英

Python:如何在特定條件下讀取目錄中的所有文件?

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

我想讀取一個目錄中的所有文件。 目錄包含以下文件:

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

當我運行腳本時,我想在控制台上以以下格式提供此文件名: ABC11。

之后,我想按排序順序讀取僅具有ABC11擴展名的所有文件。 即像這樣的第一個ABC11_1.csv,ABC11_2.csv,ABC11_3.csv。

如果用戶僅給出ABC應用程序,則必須給出錯誤消息。 如果用戶僅提供ABC1,則它是有效的應用程序,接受該請求並在目錄中檢查擴展名為ABC1的文件,如果可用,則按排序順序處理文件,如果沒有,則顯示錯誤消息。

程序代碼

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)

我正在那樣做,對我來說很好,但是其他最好的方式可以做到這一點。 請提供您的所有回復?

謝謝。

根據您的問題,以下偽代碼應該可以工作

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