If the file name is not 7 alphanumeric characters, then the entire file name is printed

Asked 2 years ago, Updated 2 years ago, 34 views

Currently speaking Python language and having difficulty implementing code. For example, in the G:\new folder path, files with formats such as '181001161609_00001_1AE_AAAABAA.bmp', 181101161609_00001_1AE_AAABBAA.bmp'.

I want to implement a code that prints out the entire file name unless there are seven of the last seven letters (AAABBAA) before .bmp.

I'm a beginner in Python, so I don't have any commands or codes. I'm sorry. I ask for your help me.

python code

2022-09-22 10:45

2 Answers

import os

files = os.listdir('YOUR_DIR_PATH')
for file in files:
  filename = os.path.splitext(file)[0] # file name and extension isolation
  last_token = filename.split('_')[-1] # Pull the last token with "_" as splitter

  If len(last_token) == 7: # If the last token has 7 lengths,
    print(last_token)
  else:
    print(filename)

That's about it

Code written on the premise that all file names have similar formats. I think you can take care of the exception according to the situation.


2022-09-22 10:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.