I'm going to show you how to write a module which can be used to tell the program which number hasn't been used.
The module should work something like this;
It has a main(path, FileName) function which asks the caller to pass it where the files are stored and what the name of the file is (without the number on the end of it). When this is passed to the module this should happen;
1. The module tests to see if the path exists
2. If the path exists, it begins a while loop to only stop when
done = True
3. In the while loop, the program will start a 'for' loop to go through and test if the File/folder name with the number on the end exists using the os module.
4. If the file/folder with a number on the end exists (e.g. Name1),
the module will add 1 to a variable which is keeping track of how many numbers it has checked.
5. If the file/folder name with a number on the end doesn't exist, it stops all of the loops and returns the number it was up to back to the caller. (e.g. 2 as in Name2 doesn't exist).
6. If the first path it tests doesn't exist, it returns an Error
So, coded out it should look something like this;
import os
def Main(path, FileName):
MaxNumb = 100#sets the maximum number to be searched for.
if os.path.exists(path+"\\"+FileName):
done = False
Num = 1#the file number it has check up to
while not done:
for i in range(0, MaxNumb): #starts the for loop
TestNum = str(Num) #Makes Num a string
TestFile = os.path.exists(path+"\\"+FileName+TestNum)
#Changes the file name to check for each time
if TestFile == True:
Num = Num + 1 #Adds 1 to the number var.
if TestFile == False:
done = True
return Num
#sends the caller the current Num var
else:
return "File does not exist!"
#Sends the caller an error
Ok so now lets try this module and see if it works.
Either copy the code above and save it into a file or download the attached file and copy it to "C:\Python25\Lib\site-packages"
(Python folder may be different in different versions of Python).
Then find somewhere on your computer and make a folder(call it whatever you want). Then inside of that folder make three new folders;
Name, Name1 and Name2.
When all this is done, open up an interactive Python window and import the module (I called mine FileNumber)
>>> Import FileNumber
>>> Number = FileNumber.Main('C:\Users\Eric\Documents\Python', 'Name')
>>> print Number
>>> 3
This means that you do not have a folder called Name3. That is what should happen if the module doesn't have an error. This is what the output will look like if an error occurs:
>>> Import FileNumber
>>> Number = FileNumber.Main('C:\Users\Eric\Documents\Python', 'Name')
>>> print Number
>>> File does not exist!
That's how you make a file numbering module!
This was my first tutorial so any suggestions or constructive criticism is welcomed! Thanks.
Attached File(s)
-
FileNumber.zip (385bytes)
Number of downloads: 117





MultiQuote






|