add a line to a file and then automatically rename it

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • halcon
    New Member
    • Jun 2007
    • 1

    add a line to a file and then automatically rename it

    Hi,
    What if I want to add a line to a file and then automatically rename it in a cycle using a sequence of numbers. I mean, if the original file has the name file0.txt then the next file should be file1.txt and the next should be file2.txt and so on.

    I hope you can give me some help here.

    Thanks
  • ghostdog74
    Recognized Expert Contributor
    • Apr 2006
    • 511

    #2
    Originally posted by halcon
    Hi,
    What if I want to add a line to a file and then automatically rename it in a cycle using a sequence of numbers. I mean, if the original file has the name file0.txt then the next file should be file1.txt and the next should be file2.txt and so on.

    I hope you can give me some help here.

    Thanks
    not tested...
    Code:
    import os,shutil
    if os.path.exists("num"):
         value=open("num").read().strip()
    lineToAdd = "new line"
    newfile ="file%s.txt" % str(int(num)+1)
    shutil.copy("file0.txt",  newfile)
    open(newfile,"a").write(line+"\n")

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Originally posted by halcon
      Hi,
      What if I want to add a line to a file and then automatically rename it in a cycle using a sequence of numbers. I mean, if the original file has the name file0.txt then the next file should be file1.txt and the next should be file2.txt and so on.

      I hope you can give me some help here.

      Thanks
      [code=Python]import os, re

      patt = r'\d+\Z'

      # seed file, name must end with one or more digits
      fn = r'X:\directory\ subdir\name999. txt'

      for i in range(5):
      fnList = list(os.path.sp litext(fn))

      num = re.search(patt, fnList[0]).group(0)
      fnList[0] = re.sub(patt, str(int(num)+1) , fnList[0])

      stringToAdd = '9876543210'

      fn1 = ''.join(fnList)
      f = open(fn1, 'w')
      f.write('%s\n%s ' % (open(fn).read( ), stringToAdd))
      f.close()
      fn = fn1[/code]

      Comment

      Working...