AttributeError: 'nt.stat_result' object ha

2019-08-09 09:12发布

问题:

I am trying to delete a files. I check the date and delete if it is older than I want. I noticed that one .zip file was not deleting. It was read only, so in a bit of test code, I used the os.chmod(path, stat.S_IWRITE) and then os.remove(path) and it worked. I put this code into my main code and got the error. I import the os and stat module in both.

Below is the test code that works, but when I put this into the bigger code I got the error and the full code this is just a def as well:

AttributeError: 'nt.stat_result' object has no attribute 'S_IWRITE'

I had checked that the dpath and dayscount are passing the path and number of days.

import os, stat

def del_file(dpath, dayscount):
    if dayscount > 10:
        if dpath[-4:]== ".zip":
            os.chmod(dpath,stat.S_IWRITE)
            os.remove(dpath)
        else:
            os.remove(dpath)
    else:
        print "File is Good"

dpath = "C:\Workspace\Test_Data.zip"
dayscount = 15
del_file(dpath, dayscount)

After reading here I found a link:Code on this page that showed some examples of importing modules. The answer said to import the module in the function. I tried this on my main code and it worked.

The main code imports os and stat at the top of the code, but this function doesn't seem to see it. And I'm not sure why. When I import it in the module it then sees it. So when put in the main code I had to add the import into the module, see below.

import os, stat

def test_date():
Code for this function

def get_month():
Code for this function

def del_file(dpath, dayscount):
    import os, stat
    print dpath
    print dayscount
    if dayscount > 10:
        if dpath[-4:]== ".zip":
            os.chmod(dpath,stat.S_IWRITE)
            #os.remove(dpath)
        else:
            os.remove(dpath)
    else:
        print "File is Good"

dpath = "C:\Workspace\Test_Data.zip"
dayscount = 13
del_file(dpath, dayscount)

回答1:

You are setting a variable with the name stat somewhere in your code (to the result of an os.stat call). This variable overshadows the stats module.

Search for stat = and rename the variable to another name, like stat_result.