Skip to main content
 首页 » 编程设计

python之按标准验证文件名

2025年05月04日7虾米哥

我是 python 脚本的新手,我想验证目录和子目录中的文件名。 验证应区分大小写。 我正在使用 python 2.6.5 操作系统:win7和xp

我提示以下用户输入:

prompt = "year" 
year = raw_input(prompt) 
prompt = "number" 
number = raw_input(prompt) 

从这里我想搜索/验证以下文件和文件夹是否存在以及它们的文件名是否正确。

文件夹结构:

..\foobar_(number)_version1\music 

子文件夹“音乐”中的文件

(year)_foobar_(number)_isnice.txt 
(year)_itis(number)hot_today.txt 
(year)_anything_is(number)possible.txt 
(year)_something_{idont_want_to_check_this_part}_(number)_canbe_anything.txt 

请注意,包括下划线在内的所有文本始终相同,因此应该始终正确,但 () 或 {} 之间的内容除外。 我想将结果输出到一个 txt 文件,该文件报告文件名是否正确。

实现此目标的最合乎逻辑的方法是什么? 我已经阅读了 lib 文档 fnmatch(.fnmatchcase)、RE 和 os(.path.isfile) 并在此处搜索示例,但我就是不知道从哪里开始以及如何开始。

谁能指出我正确的方向?

[编辑] 一旦我的脚本有了工作基础,我就会发布我的代码以供引用或帮助他人。

[edit2] 我的第一个非 hello world 脚本

import os 
import re 
 
#output : 
file_out = "H:\\output.txt" 
f_out = open(file_out, 'w') 
 
print "-------start-script----------" 
 
#input 
prompt = "enter 4 digit year: " 
year = raw_input(prompt) 
prompt = "enter 2 digit number: " 
number = raw_input(prompt) 
 
print "the chosen year is %s" % (year) 
print "the chosen number is %s" % (number) 
 
f_out.write ("start log!\n") 
f_out.write ("------------------------------------------\n") 
f_out.write ("the chosen year is %s\n" % (year)) 
f_out.write ("the chosen number is %s\n" % (number)) 
 
#part i'm working on 
 
print "end script" 
f_out.write ("------------------------------------------\n") 
f_out.write ("end script\n") 
 
#close file 
f_out.close() 

请您参考如下方法:

查看 glob 模块 - 这将帮助您获取当前目录中的文件列表:

import glob 
 
year = raw_input('Year: ')        # Example: Year: 2009 
number = raw_input('Number: ')    # Example: Number: 12 
filenames = glob.glob('{year}_*{number}*'.format(year=year, number=number)) 

文件名将是当前目录中满足以下条件的任何内容:

  1. 以 2009_ 开头
  2. 任意数量的字符,直到匹配 12
  3. 12 之后的任意数量的字符。

os.path.exists 是检查文件是否存在的好方法,或者 os.path.isfile 如果您想确保它确实是一个文件而不是像文件一样命名的目录。对于 Python3,检查 these docs ,并喜欢 link ghostbust555 mentioned说,如果你打算做除了验证它们存在之外的任何事情,请注意竞争条件。


根据您的评论,这看起来像是正则表达式的工作。您需要编写的伪代码如下所示:

for filename in list of filenames: 
    if filename is not valid: 
        print "<filename> is not valid!" 

除了实际的模式,实际的 python 代码可能如下所示:

import os 
import re 
 
pattern = 'Put your actual pattern here' 
 
# For a different directory, change the . to whatever the directory should be 
for filename in os.listdir('.'): 
    if not re.match(pattern, filename): 
        print("Bad filename: ", filename)