def _MakeObject(self, objType, fullpath, isDir=False): stat = os.stat(fullpath) ret, shfileinfo = shell.SHGetFileInfo( fullpath, 0, shellcon.SHGFI_ICON | shellcon.SHGFI_TYPENAME) obj = objType() if isDir: size = -1 else: size = stat.st_size # エラー対策 mtime = 0 ctime = 0 if stat.st_mtime <= 32536799999: mtime = stat.st_mtime if stat.st_ctime <= 32536799999: ctime = stat.st_ctime obj.Initialize( os.path.dirname(fullpath), # directory os.path.basename(fullpath), # basename fullpath, size, # size datetime.datetime.fromtimestamp(mtime, datetime.timezone.utc), # modDate win32file.GetFileAttributes(fullpath), # attributes shfileinfo[4], # typeString datetime.datetime.fromtimestamp(ctime, datetime.timezone.utc), # creationDate win32api.GetShortPathName(fullpath), # shortName shfileinfo[0], # hIcon relpath=os.path.relpath(fullpath, self.rootDirectory) ) return obj
def clientarchive(dest, edict, busy=None): #walk client subfolders lst = os.listdir(edict['DATAPATH']) nd = dest + '/Clients-' + datemarker() if os.path.exists(nd): nx = 0 nA = ord('A') nn = nA while os.path.exists(nd + nn): nx += 1 nn = chr(nA + nx) nd = nd + nn try: os.mkdir(nd) except: pass for d in lst: dp = edict['DATAPATH'] + '\\' + d if not os.path.isdir(dp): continue try: ival = win32file.GetFileAttributes(dp) sh = ival & (win32file.FILE_ATTRIBUTE_HIDDEN | win32file.FILE_ATTRIBUTE_SYSTEM) if sh == 0: if busy: busy.newstatus(dp) #print dp pass except: print 'unable to get A' return 1 ans = zipafolder(nd, dp, edict['DATAPATH'] + '\\', sh) if ans: return 2
def Delete(self, szItem, nOpSettings): #if __WXMSW__ strPath = self.m_strCurDir if not (self.m_strCurDir[-1] == '\\' or self.m_strCurDir[-1] == '/'): strPath += '/' strPath += szItem #print "bei delete", strPath dwAttr = win32file.GetFileAttributes(strPath) #//TOFIX add FILE_ATTRIBUTE_SYSTEM support #print "0" if ((-1 != dwAttr) and ((dwAttr & win32con.FILE_ATTRIBUTE_READONLY) == win32con.FILE_ATTRIBUTE_READONLY)): #//if the style was not set, ask the user what to do #print "1" if (not (nOpSettings & OPF_DEL_ALL_RO_FILES)): #print "2" #print "delete1" nOpSettings |= OpDeleteFileDlgThreadsafe(strPath) #print "delete2" if ((OPF_ABORT & nOpSettings) or (OPF_SKIP & nOpSettings)): return False #print "delete3" ''' /* if(m_bRecycleBin) { //NOTE: this one does not need removing the style to delete the file if(MoveToTrash(strPath)) return true; } */ ''' #//Hard delete (if required or recycle failed) if (-1 != dwAttr and dwAttr & win32con.FILE_ATTRIBUTE_READONLY): #//remove read-only style (so delete API won't fail) dwAttr &= ~(win32con.FILE_ATTRIBUTE_READONLY) win32file.SetFileAttributes(strPath, dwAttr) #//TOFIX add wipe support (global ini settings) if (dwAttr & win32con.FILE_ATTRIBUTE_DIRECTORY): #//NOTE: dir should be empty at this point #return (::RemoveDirectory(strPath) > 0); #win32file.RemoveDirectory (strPath) #TODO:Anzeige nachher wieder richtig (refreshen) #print "delete in dir" #TOO remove? #self.walktree(strPath, self.removefile, self.removedir) os.rmdir(strPath) #TODO: evaluate: really true? return True #os.removedirs(strPath) else: os.remove(strPath) #TODO: evaluate: really true? return True '''
def copyDirOverride(src, dst, exception=None): src = System.local_encode(src) dst = System.local_encode(dst) if not os.path.isdir(src): return if exception is None: exception = [] try: attr = win32file.GetFileAttributes(src) if attr & FILE_ATTRIBUTE_SYSTEM and attr & FILE_ATTRIBUTE_REPARSE_POINT: return win32file.SetFileAttributes(dst, attr) except: #print "Unable to setAttribute of",dst pass if not os.path.isdir(dst): os.makedirs(dst) dirs = None try: dirs = os.listdir(src) except Exception, err: return
def is_hiden_file(file_Path): if is_windows_system(): fileAttr = win32file.GetFileAttributes(file_Path) if fileAttr & win32con.FILE_ATTRIBUTE_HIDDEN: return True return False return False
def isHidenFile(filePath): if 'Windows' in platform.system(): import win32file, win32con fileAttr = win32file.GetFileAttributes(filePath) if fileAttr & win32con.FILE_ATTRIBUTE_HIDDEN: return True return False return False
def is_sparse(path): supported = get_sparse_files_support(path) if not supported: return False if os.name == 'nt': return bool( win32file.GetFileAttributes(path) & FILE_ATTRIBUTE_SPARSE_FILE) return False
def fileattributeisset(filename, fileattr): """ Check if a given Fileattribute is set. :return: Inforamtion if Fileattribute is set. :rtype: boolean """ return bool(win32file.GetFileAttributes(filename) & fileattr)
def togglefileattribute(filename, fileattribute, value): #switches the file attribute to on or off based on the true or false value passed bitvector = win32file.GetFileAttributes(filename) if value: bitvector |= fileattribute else: bitvector &= ~fileattribute win32file.SetFileAttributes(filename, bitvector)
def testMoreFiles(self): # Create a file in the %TEMP% directory. testName = os.path.join(win32api.GetTempPath(), "win32filetest.dat") desiredAccess = win32file.GENERIC_READ | win32file.GENERIC_WRITE # Set a flag to delete the file automatically when it is closed. fileFlags = win32file.FILE_FLAG_DELETE_ON_CLOSE h = win32file.CreateFile(testName, desiredAccess, win32file.FILE_SHARE_READ, None, win32file.CREATE_ALWAYS, fileFlags, 0) # Write a known number of bytes to the file. data = "z" * 1025 win32file.WriteFile(h, data) self.failUnless( win32file.GetFileSize(h) == len(data), "WARNING: Written file does not have the same size as the length of the data in it!" ) # Ensure we can read the data back. win32file.SetFilePointer(h, 0, win32file.FILE_BEGIN) hr, read_data = win32file.ReadFile(h, len(data) + 10) # + 10 to get anything extra self.failUnless(hr == 0, "Readfile returned %d" % hr) self.failUnless(read_data == data, "Read data is not what we wrote!") # Now truncate the file at 1/2 its existing size. newSize = len(data) / 2 win32file.SetFilePointer(h, newSize, win32file.FILE_BEGIN) win32file.SetEndOfFile(h) self.failUnless( win32file.GetFileSize(h) == newSize, "Truncated file does not have the expected size!") # GetFileAttributesEx/GetFileAttributesExW tests. self.failUnless( win32file.GetFileAttributesEx( testName) == win32file.GetFileAttributesExW(testName), "ERROR: Expected GetFileAttributesEx and GetFileAttributesExW to return the same data" ) attr, ct, at, wt, size = win32file.GetFileAttributesEx(testName) self.failUnless( size == newSize, "Expected GetFileAttributesEx to return the same size as GetFileSize()" ) self.failUnless( attr == win32file.GetFileAttributes(testName), "Expected GetFileAttributesEx to return the same attributes as GetFileAttributes" ) h = None # Close the file by removing the last reference to the handle! self.failUnless(not os.path.isfile(testName), "After closing the file, it still exists!")
def is_hidden_file(self, file_path): """ 判断 windows 系统下,文件是否为隐藏文件,是则返回 True """ if 'Windows' in platform.system(): file_attr = win32file.GetFileAttributes( file_path) # 获取文件属性得到的是 int 值,例如 128 、32 等 # FILE_ATTRIBUTE_HIDDEN 拿到的是 2 数字,与上行代码做 & 运算,结果非 0 说明是隐藏文件 if file_attr & win32con.FILE_ATTRIBUTE_HIDDEN: return True return False return False
def IsSymLink(filename): import win32file # <Module 'win32file' has not 'GetFileAttributes' member, but source is unavailable. Consider adding this module to extension-pkg-whitelist if you want to perform analysis based on run-time introspection of living objects.> pylint: disable = I1101 file_attribute_reparse_point = 1024 return os.path.exists(filename) and win32file.GetFileAttributes( filename ) & file_attribute_reparse_point == file_attribute_reparse_point
def fget(self): try: import win32file except: raise NotSupportedException("this method is win32 only") if os.path.exists(self.original_path): return FileAttributes(win32file.GetFileAttributes(self.original_path)) else: raise DirectoryNotFoundException( "'%s' not found" % self.original_path)
def fileAttr(f, dummy): ret = '' attr = win32file.GetFileAttributes(f) attrs = [(win32file.FILE_ATTRIBUTE_READONLY, 'r'), (win32file.FILE_ATTRIBUTE_HIDDEN, 'h'), (win32file.FILE_ATTRIBUTE_SYSTEM, 's')] for bit, char in attrs: if attr & bit: ret += char else: ret += ' ' return ret
def make_file_dict_python(filename): """Create the data dictionary using a Python call to os.lstat We do this on Windows since Python's implementation is much better than the one in cmodule.c Eventually, we will move to using this on all platforms since CPUs have gotten much faster than they were when it was necessary to write cmodule.c """ try: statblock = os.lstat(filename) except os.error: return {'type':None} data = {} mode = statblock[stat.ST_MODE] if stat.S_ISREG(mode): type = 'reg' elif stat.S_ISDIR(mode): type = 'dir' elif stat.S_ISCHR(mode): type = 'dev' s = statblock.st_rdev data['devnums'] = ('c',) + (s >> 8, s & 0xff) elif stat.S_ISBLK(mode): type = 'dev' s = statblock.st_rdev data['devnums'] = ('b',) + (s >> 8, s & 0xff) elif stat.S_ISFIFO(mode): type = 'fifo' elif stat.S_ISLNK(mode): type = 'sym' data['linkname'] = os.readlink(filename) elif stat.S_ISSOCK(mode): type = 'sock' else: raise C.UnknownFileError(filename) data['type'] = type data['size'] = statblock[stat.ST_SIZE] data['perms'] = stat.S_IMODE(mode) data['uid'] = statblock[stat.ST_UID] data['gid'] = statblock[stat.ST_GID] data['inode'] = statblock[stat.ST_INO] data['devloc'] = statblock[stat.ST_DEV] data['nlink'] = statblock[stat.ST_NLINK] if os.name == 'nt': attribs = win32file.GetFileAttributes(filename) if attribs & winnt.FILE_ATTRIBUTE_REPARSE_POINT: data['type'] = 'sym' data['linkname'] = None if not (type == 'sym' or type == 'dev'): # mtimes on symlinks and dev files don't work consistently data['mtime'] = long(statblock[stat.ST_MTIME]) data['atime'] = long(statblock[stat.ST_ATIME]) data['ctime'] = long(statblock[stat.ST_CTIME]) return data
def setHidden(fd, hide): global hidden print fd, if useWin32: fa = win32file.GetFileAttributes(fd) print fa, if hide: win32file.SetFileAttributes(fd, fa | hidden) else: if fa & hidden: win32file.SetFileAttributes(fd, fa ^ hidden) print win32file.GetFileAttributes(fd) else: if hide: setter = '+h' else: setter = '-h' # code = os.spawnlp( os.P_WAIT, 'attrib', setter, fd, '/s', '/d') code = os.system('attrib %s %s /s /d' % (setter, fd)) print code
def IsBackupNeeded(edict): # get today today = time.localtime() tagfile = edict['PROGRAMPATH'] + '/lastbackup.txt' if os.path.exists(tagfile): tagdate = os.stat(tagfile) tagd = time.localtime(tagdate[8]) if today.tm_year == tagd.tm_year and today.tm_mon == tagd.tm_mon: return 0 else: fout = open(tagfile, 'w') fout.write(time.asctime()) fout.close() return 1 #scan clients folders and examine SMR,AT,EXP folder dates fl = glob.glob(edict['DATAPATH'] + '/*') isnew = 0 for f in fl: if os.path.isdir(f): fin = glob.glob(f + '/*') for fd in fin: if os.path.isdir(fd): iflist = glob.glob(fd + '/*') for ifile in iflist: fattrs = win32file.GetFileAttributes(ifile) if fattrs & win32con.FILE_ATTRIBUTE_ARCHIVE == 0: continue # if has been archived already fdate = os.stat(ifile)[8] fff = time.localtime(fdate) if fff.tm_year >= tagd.tm_year and fff.tm_mon > tagd.tm_mon: isnew = 1 break if isnew: break if isnew: break fout = open(tagfile, 'w') fout.write(time.asctime()) fout.close() if isnew: return 1 # if "new" return yes return 0
def func(spec_directory, show_hidden=False): dirnum = 0 # 文件夹数量 filenum = 0 # 文件数量(不计文件夹) num = 0 # 总文件数量(计文件夹) for root, dirs, files in os.walk(spec_directory): for name in dirs: dirnum = dirnum + 1 if show_hidden == True: for fn in os.listdir(spec_directory): num = num + 1 if show_hidden == False: for i in os.listdir(spec_directory): flag = win32file.GetFileAttributes(spec_directory + '\\' + i) if flag & 2 != 0: num = num else: num = num + 1 filenum = num - dirnum print("文件夹个数:", dirnum) print("文件个数:", filenum)
def file_sum(spec_directory, show_hidden=False): dirs_num = 0 dirs = [] files_num = 0 files = [] for i in os.listdir(spec_directory): flag = win32file.GetFileAttributes(spec_directory + '\\' + i) is_hiden = flag & win32con.FILE_ATTRIBUTE_HIDDEN if is_hiden and show_hidden == False: continue else: if os.path.isfile(spec_directory + i): files_num += 1 files.append(i) else: dirs_num += 1 dirs.append(i) print("文件总数为%d:" % files_num) print(files) print("文件夹总数为%d:" % dirs_num) print(dirs)
def show(self): DIR = self.path dirs_num = 0 dirs = [] files_num = 0 files = [] for i in os.listdir(DIR): flag = win32file.GetFileAttributes(DIR + '\\' + i) is_hiden = flag & win32con.FILE_ATTRIBUTE_HIDDEN if is_hiden: continue else: if os.path.isfile(DIR + i): files_num += 1 files.append(i) else: dirs_num += 1 dirs.append(i) print("文件总数为%d:" % files_num) print(files) print("文件夹总数为%d:" % dirs_num) print(dirs)
def expand(self, item): print "********************************" if item.text(0) == u'此电脑': pass else: if hasattr(item, 'takeChildren'): item.takeChildren() files = os.listdir(item.path) files.sort() for f in files: path = item.path.rstrip( '/') + '\\' + f # item.path.rstrip("/")为去除“/”并且是字符串右边的 if os.path.isdir(path): flag = win32file.GetFileAttributes(path) if flag & 2 != 0: pass else: Iconitem = QtGui.QIcon( 'D:/python2.7/Lib/site-packages/PySide/examples/demos/qtdemo/images/open.png' ) newItem = QtGui.QTreeWidgetItem(item, [f]) newItem.setIcon(0, Iconitem) newItem.path = path QtGui.QTreeWidgetItem(newItem, '')
def clientarchive(dest, edict): #walk client subfolders lst = os.listdir(edict['DATAPATH']) nd = dest + '/Clients-' + datemarker() try: os.mkdir(nd) except: pass for d in lst: dp = edict['DATAPATH'] + '\\' + d if not os.path.isdir(dp): continue try: ival = win32file.GetFileAttributes(dp) sh = ival & (win32file.FILE_ATTRIBUTE_HIDDEN | win32file.FILE_ATTRIBUTE_SYSTEM) if sh == 0: print dp except: print 'unable to get A' return 1 ans = zipafolder(nd, dp, edict['DATAPATH'] + '\\', sh) if ans: return 2
def can_open(self): import win32file return win32file.GetFileAttributes( (self.named_pipe_path)) == win32file.FILE_ATTRIBUTE_NORMAL