0

I'm trying to find files which are 30 days old in a specific directory, move them to a new folder and compress that folder, however when I execute my script, Python complains about Python AttributeError: 'str' object has no attribute 'append'

import os 
import time 
import sys 
import shutil 
import tarfile
import sys
import os.path
import _strptime 
from array import*


path="/Data/"
now = time.time()
export = os.path.join(path+"archives")

f=[]
m=[]
for root, dirs, files in os.walk(path): #List files in directory 
         for basename in files:
            f.append(os.path.join(root,basename))            
            print(f)
            for i in f:
                mtime=os.stat(i).st_mtime            
                print(i, mtime)
                if mtime > now - 7 * 86400:           
                    m.append(i) 
                    os.makedirs(export,0777)
                    for f in m: 
                        print("moving file", f,  "to",  export)
                        shutil.move(f, export) 
                        tarfile.open(export +time.strftime("%d-%Y-%m") +'.tar.gz', 'w:gz')

                    else:
                        print("Nothing to do")
7
  • 1
    possible duplicate of AttributeError: 'str' object has no attribute 'append' Commented Jun 3, 2014 at 14:15
  • 4
    Because you cannot append to a string. Commented Jun 3, 2014 at 14:15
  • Next time - don't just put your code here. Show the error message & the specific part in the code that caused it. Commented Jun 3, 2014 at 14:16
  • 2
    Is this all your code? You're not actually calling .append() on a string anywhere Commented Jun 3, 2014 at 14:18
  • 1
    it is actually a good question as it shows the weird (in my opinion) python design principle, where loop variables have more "global" scope than expected and overwrite outer variables Commented Jun 3, 2014 at 14:24

1 Answer 1

3

You are redeclaring f variable. It is a list on the begining, but then used in the inner loop

for f in m: 

which makes f a string

simply change a name of inner loop variable to something different like

for filename in m: 
    print("moving file", filename,  "to",  export)
    shutil.move(filename, export) 
    tarfile.open(export +time.strftime("%d-%Y-%m") +'.tar.gz', 'w:gz')

It is a quite common issue with python, if you declare a variable as the "inner loop variable" it has the same scope as the "outer" loop so it overwrites its values.

x = 5
print x #prints 5
for a in range(10):
    for x in range(10):
        y=1
print x #prints 9
sth = [ 1 for x in range(20) ]
print x #prints 19
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.