I’m fairly new to python scripting and I want to verify file names in a directory and subdirectory.
The verification should be case sensitive.
I’m using python 2.6.5
OS: win7 and xp
I prompt for the following user input:
prompt = "year"
year = raw_input(prompt)
prompt = "number"
number = raw_input(prompt)
From here I want to search/verify that the following files and folders exist and their filename is correct.
folderstructure:
..\foobar_(number)_version1\music
Files in subfolder ‘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
Note that all text including underscores are always the same, and thus should always be right, except for the things between () or {}.
I want to output the results to a txt file which reports if the filename is correct or not.
What is the most logical method to archieve this?
I’ve read the lib documentation fnmatch(.fnmatchcase), RE and os(.path.isfile) and searched here for examples, but I just can’t figure out where and how to start.
Can anyone point me in the right direction?
[edit]
As soon as my script has the working basics I’ll post my code for reference or to help others.
[edit2] my first non-hello world script
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()
Take a look at the glob module – this will help you get a list of files in the current directory:
Filenames will be anything in the current directory that meets the following criteria:
2009_1212.os.path.existsis a good way to check if the file exists, oros.path.isfileif you want to make sure that it’s really a file and not a directory named like a file. For Python3, check these docs, and like the link ghostbust555 mentioned says, be careful of race conditions if you plan on doing anything besides verifying their existence.Based on your comment, it looks like this is a job for regular expressions. The pseudo code for what you need to write looks something like this:
Aside from the actual pattern, the actual python code could look like this: