[Tutor] Need Advice About Saving Files that Already Exist.
Daniel
daniel@longbeach.goldinc.com
Fri, 11 May 2001 14:07:45 -0500 (CDT)
Hey James,
I'll give it a shot. This might help you out.
Here is an example from my pc. The dir I use is /tmp. and the filename
that I use I give as an argument. .. it seems work work ok. heh :-)
(dev.bart.~): ls /tmp/
lost+found/ mysql.sock= screens/ uscreens/
(dev.bart.~): python movefiles.py bla
then no one has our filename and we can write to it
(dev.bart.~): touch /tmp/bla
(dev.bart.~): ls /tmp/
bla lost+found/ mysql.sock= screens/ uscreens/
(dev.bart.~): python movefiles.py bla
old file is [** bla **] new file is [** bla.1 **]
(dev.bart.~): ls /tmp/
bla bla.1 lost+found/ mysql.sock= screens/ uscreens/
(dev.bart.~): python movefiles.py bla
old file is [** bla.1 **] new file is [** bla.2 **]
(dev.bart.~): python movefiles.py bla
old file is [** bla.2 **] new file is [** bla.3 **]
(dev.bart.~): python movefiles.py bla
old file is [** bla.3 **] new file is [** bla.4 **]
(dev.bart.~): ls /tmp/
bla bla.1 bla.2 bla.3 bla.4 lost+found/ mysql.sock= screens/
uscreens/
#BEGIN CODE PASTE
import os, string, sys, shutil
DIR = '/tmp'
mynewfile = sys.argv[1]
dir_listing = os.listdir(DIR)
HEH = []
#for each file in our directory
for i in dir_listing:
if os.path.isfile("%s/%s" %(DIR, i)) == 1: #if it's a file and not a
#directory
file = string.split(i, '.') #split it by .
if file[0] == mynewfile: HEH.append(file)
#for all the files in our dir that have a prefix of the file we
#want append them to the HEH list
if len(HEH) == 0:
print "then no one has our filename and we can write to it"
#enter in file writing here for the first time
sys.exit(0)
for i in HEH: #for each line in our HEH list
try:
#try to find the next suffix, if that fails then (see next)
newfooter = int(file[1])+1
firstpart = file[0]
newfile = "%s.%s" %(firstpart, newfooter)
oldfile = "%s.%s" %(firstpart, file[1])
except:
# then it doesn't have a suffix
firstpart = file[0]
newfooter = 1 #so we give it the first one
newfile = "%s.%s" %(firstpart, newfooter)
oldfile = "%s" %(firstpart)
shutil.copyfile("%s/%s" % (DIR, oldfile), "%s/%s" % (DIR, newfile))
#this is the end, I'm copying here b/c I want the file numbers to get
#larger for example reasons, you would put your write to file statement
here with the new
#file to write to being the var newfile
print "old file is [**",oldfile,"**] new file is [**",newfile,"**]"
#END CODE PASTE
--
Daniel