我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用stat.ST_SIZE。
def serve(self, request, path): # the following code is largely borrowed from `django.views.static.serve` # and django-filetransfers: filetransfers.backends.default fullpath = os.path.join(settings.PRIVATE_MEDIA_ROOT, path) if not os.path.exists(fullpath): raise Http404('"{0}" does not exist'.format(fullpath)) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) content_type = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified(content_type=content_type) response = HttpResponse(open(fullpath, 'rb').read(), content_type=content_type) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) # filename = os.path.basename(path) # response['Content-Disposition'] = smart_str(u'attachment; filename={0}'.format(filename)) return response
def walker(arg, dirname, fnames): d = os.getcwd() os.chdir(dirname) try: fnames.remove('Thumbs') except ValueError: pass for f in fnames: if not os.path.isfile(f): continue size = os.stat(f)[stat.ST_SIZE] if size < 100: continue if filesBySize.has_key(size): a = filesBySize[size] else: a = [] filesBySize[size] = a a.append(os.path.join(dirname, f)) os.chdir(d)
def get_last_offset(self, f): st = os.fstat(f.fileno()) ino = st[stat.ST_INO] size = st[stat.ST_SIZE] try: last = self.read_last_stat() except IOError: # no such file last = {'inode': 0, 'offset': 0} if last['inode'] == ino and last['offset'] <= size: return last['offset'] else: return 0
def readData(self, filename, file_index): # Open file and read file size self.warning("Load input file: %s" % filename) data = open(filename, 'rb') orig_filesize = fstat(data.fileno())[ST_SIZE] if not orig_filesize: raise ValueError("Input file (%s) is empty!" % filename) # Read bytes if self.max_size: data = data.read(self.max_size) else: data = data.read() # Display message if input is truncated if len(data) < orig_filesize: percent = len(data) * 100.0 / orig_filesize self.warning("Truncate file to %s bytes (%.2f%% of %s bytes)" \ % (len(data), percent, orig_filesize)) # Convert to Python array object return array('B', data)
def multipart_encode(vars, files, boundary = None, buffer = None): if boundary is None: boundary = mimetools.choose_boundary() if buffer is None: buffer = '' for(key, value) in vars: buffer += '--%s\r\n' % boundary buffer += 'Content-Disposition: form-data; name="%s"' % key buffer += '\r\n\r\n' + value + '\r\n' for(key, fd) in files: file_size = os.fstat(fd.fileno())[stat.ST_SIZE] filename = fd.name.split('/')[-1] contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' buffer += '--%s\r\n' % boundary buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename) buffer += 'Content-Type: %s\r\n' % contenttype # buffer += 'Content-Length: %s\r\n' % file_size fd.seek(0) buffer += '\r\n' + fd.read() + '\r\n' buffer += '--%s--\r\n\r\n' % boundary return boundary, buffer
def serve(self, request, file_obj, **kwargs): fullpath = file_obj.path # the following code is largely borrowed from `django.views.static.serve` # and django-filetransfers: filetransfers.backends.default if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) content_type_key = 'mimetype' if LTE_DJANGO_1_4 else 'content_type' response_params = {content_type_key: self.get_mimetype(fullpath)} if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified(**response_params) response = HttpResponse(open(fullpath, 'rb').read(), **response_params) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) self.default_headers(request=request, response=response, file_obj=file_obj, **kwargs) return response
def test_files(self): """ Test reading and writing of files via rand functions. """ # Write random bytes to a file tmpfile = self.mktemp() # Make sure it exists (so cleanup definitely succeeds) fObj = file(tmpfile, 'w') fObj.close() try: rand.write_file(tmpfile) # Verify length of written file size = os.stat(tmpfile)[stat.ST_SIZE] self.assertEquals(size, 1024) # Read random bytes from file rand.load_file(tmpfile) rand.load_file(tmpfile, 4) # specify a length finally: # Cleanup os.unlink(tmpfile)
def GetItemData(self, colid, colData): fmt_id, pid = colid fmt_id==self._reg_clsid_ flags, attr, reserved, ext, name = colData if ext.lower() not in [".py", ".pyw"]: return None if pid==0: ext = ".pyc" else: ext = ".pyo" check_file = os.path.splitext(name)[0] + ext try: st = os.stat(check_file) return st[stat.ST_SIZE] except OSError: # No file return None
def gen_folder_listing(path): l = os.listdir(path) s = '<?xml version="1.0"?>\n<folder-listing>\n' for i in l: objpath = os.path.join(path, i) if os.path.isdir(objpath): args = (i, unix2bluetime(os.stat(objpath)[stat.ST_CTIME])) s += ' <folder name="%s" created="%s" />' % args else: args = (i, unix2bluetime(os.stat(objpath)[stat.ST_CTIME]), os.stat(objpath)[stat.ST_SIZE]) s += ' <file name="%s" created="%s" size="%s" />' % args s += "</folder-listing>\n" if sys.version_info.major < 3: s = unicode(s) return s
def copy_file_if_modified(src_path, dest_path): """Only copies the file from the source path to the destination path if it doesn't exist yet or it has been modified. Intended to provide something of an optimisation when a project has large trees of assets.""" # if the destination path is a directory, delete it completely - we assume here we are # writing a file to the filesystem if os.path.isdir(dest_path): shutil.rmtree(dest_path) must_copy = False if not os.path.exists(dest_path): must_copy = True else: src_stat = os.stat(src_path) dest_stat = os.stat(dest_path) # if the size or last modified timestamp are different if ((src_stat[stat.ST_SIZE] != dest_stat[stat.ST_SIZE]) or (src_stat[stat.ST_MTIME] != dest_stat[stat.ST_MTIME])): must_copy = True if must_copy: shutil.copy2(src_path, dest_path)
def setUp(self): if os.path.exists(TESTFN): mode = 'r+b' else: mode = 'w+b' with self.open(TESTFN, mode) as f: current_size = os.fstat(f.fileno())[stat.ST_SIZE] if current_size == size+1: return if current_size == 0: f.write(b'z') f.seek(0) f.seek(size) f.write(b'a') f.flush() self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
def _read_write_test(self, path): """ Verify that ``rand.write_file`` and ``rand.load_file`` can be used. """ # Create the file so cleanup is more straightforward with open(path, "w"): pass try: # Write random bytes to a file rand.write_file(path) # Verify length of written file size = os.stat(path)[stat.ST_SIZE] self.assertEqual(1024, size) # Read random bytes from file rand.load_file(path) rand.load_file(path, 4) # specify a length finally: # Cleanup os.unlink(path)
def CheckLoaderModule(dll_name): suffix = "" if is_debug_build: suffix = "_d" template = os.path.join(this_dir, "PyISAPI_loader" + suffix + ".dll") if not os.path.isfile(template): raise ConfigurationError( "Template loader '%s' does not exist" % (template,)) # We can't do a simple "is newer" check, as the DLL is specific to the # Python version. So we check the date-time and size are identical, # and skip the copy in that case. src_stat = os.stat(template) try: dest_stat = os.stat(dll_name) except os.error: same = 0 else: same = src_stat[stat.ST_SIZE]==dest_stat[stat.ST_SIZE] and \ src_stat[stat.ST_MTIME]==dest_stat[stat.ST_MTIME] if not same: log(2, "Updating %s->%s" % (template, dll_name)) shutil.copyfile(template, dll_name) shutil.copystat(template, dll_name) else: log(2, "%s is up to date." % (dll_name,))
def walker(arg, dirname, fnames): d = os.getcwd() os.chdir(dirname) global filesBySize try: fnames.remove('Thumbs') except ValueError: pass for f in fnames: if not os.path.isfile(f): continue size = os.stat(f)[stat.ST_SIZE] #print f + " size: " + str(size) if size < 100: continue if filesBySize.has_key(size): a = filesBySize[size] else: a = [] filesBySize[size] = a a.append(os.path.join(dirname, f)) os.chdir(d)
def test_files(self): """ Test reading and writing of files via rand functions. """ # Write random bytes to a file tmpfile = self.mktemp() # Make sure it exists (so cleanup definitely succeeds) fObj = open(tmpfile, 'w') fObj.close() try: rand.write_file(tmpfile) # Verify length of written file size = os.stat(tmpfile)[stat.ST_SIZE] self.assertEquals(size, 1024) # Read random bytes from file rand.load_file(tmpfile) rand.load_file(tmpfile, 4) # specify a length finally: # Cleanup os.unlink(tmpfile)
def updateDisplay(self, file_list): """""" for path in file_list: file_stats = os.stat(path) creation_time = time.strftime( "%m/%d/%Y %I:%M %p", time.localtime(file_stats[stat.ST_CTIME])) modified_time = time.strftime( "%m/%d/%Y %I:%M %p", time.localtime(file_stats[stat.ST_MTIME])) file_size = file_stats[stat.ST_SIZE] if file_size > 1024: file_size = file_size / 1024.0 file_size = "%.2f KB" % file_size self.file_list.append(FileInfo(path, creation_time, modified_time, file_size)) self.olv.SetObjects(self.file_list)
def generateOVF( name, osname, osid, diskname, disksize, mem=1024, cpus=1, vmname='Mininet-VM', vminfo='A Mininet Virtual Machine' ): """Generate (and return) OVF file "name.ovf" name: root name of OVF file to generate osname: OS name for OVF (Ubuntu | Ubuntu 64-bit) osid: OS ID for OVF (93 | 94 ) diskname: name of disk file disksize: size of virtual disk in bytes mem: VM memory size in MB cpus: # of virtual CPUs vmname: Name for VM (default name when importing) vmimfo: Brief description of VM for OVF""" ovf = name + '.ovf' filesize = stat( diskname )[ ST_SIZE ] params = dict( osname=osname, osid=osid, diskname=diskname, filesize=filesize, disksize=disksize, name=name, mem=mem, cpus=cpus, vmname=vmname, vminfo=vminfo ) xmltext = OVFTemplate % params with open( ovf, 'w+' ) as f: f.write( xmltext ) return ovf
def get_st_size(file_path): if type(file_path) == list: total_size = 0 for fl in file_path: if os.path.exists(fl): total_size += os.stat(fl)[ST_SIZE] return total_size else: return os.stat(file_path)[ST_SIZE]
def get_content_size(self): """Retrieve the total size of the resource at the given path. This method may be overridden by subclasses. .. versionadded:: 3.1 .. versionchanged:: 4.0 This method is now always called, instead of only when partial results are requested. """ stat_result = self._stat() return stat_result[stat.ST_SIZE]
def _file_size(f): st = os.fstat(f.fileno()) return st[stat.ST_SIZE]
def getsize(self): st = self.statinfo if not st: self.restat() st = self.statinfo return st[ST_SIZE]
def fileSize(file): """I'll try my damndest to determine the size of this file object. """ size = None if hasattr(file, "fileno"): fileno = file.fileno() try: stat_ = os.fstat(fileno) size = stat_[stat.ST_SIZE] except: pass else: return size if hasattr(file, "name") and path.exists(file.name): try: size = path.getsize(file.name) except: pass else: return size if hasattr(file, "seek") and hasattr(file, "tell"): try: try: file.seek(0, 2) size = file.tell() finally: file.seek(0, 0) except: pass else: return size return size
def listMessages(self, i=None): """Return a list of lengths of all files in new/ and cur/ """ if i is None: ret = [] for mess in self.list: if mess: ret.append(os.stat(mess)[stat.ST_SIZE]) else: ret.append(0) return ret return self.list[i] and os.stat(self.list[i])[stat.ST_SIZE] or 0
def GenerateFrozenResource(rc_name, output_name, h_name = None): """Converts an .rc windows resource source file into a python source file with the same basic public interface as the rest of this module. Particularly useful for py2exe or other 'freeze' type solutions, where a frozen .py file can be used inplace of a real .rc file. """ rcp = Parse(rc_name, h_name) in_stat = os.stat(rc_name) out = open(output_name, "wt") out.write("#%s\n" % output_name) out.write("#This is a generated file. Please edit %s instead.\n" % rc_name) out.write("__version__=%r\n" % __version__) out.write("_rc_size_=%d\n_rc_mtime_=%d\n" % (in_stat[stat.ST_SIZE], in_stat[stat.ST_MTIME])) out.write("class StringDef:\n") out.write("\tdef __init__(self, id, idNum, value):\n") out.write("\t\tself.id = id\n") out.write("\t\tself.idNum = idNum\n") out.write("\t\tself.value = value\n") out.write("\tdef __repr__(self):\n") out.write("\t\treturn \"StringDef(%r, %r, %r)\" % (self.id, self.idNum, self.value)\n") out.write("class FakeParser:\n") for name in "dialogs", "ids", "names", "bitmaps", "icons", "stringTable": out.write("\t%s = \\\n" % (name,)) pprint.pprint(getattr(rcp, name), out) out.write("\n") out.write("def Parse(s):\n") out.write("\treturn FakeParser()\n") out.close()
def _WalkCallback(self, arg, directory, files): # callback function for os.path.walk - no need to be member, but its # close to the callers :) callback, total_list = arg for file in files: fqn = os.path.join(directory, file).lower() if file.endswith(".pyc") or file.endswith(".pyo"): # See below - total_list == None means delete files, # otherwise it is a list where the result is stored. Its a # list simply due to the way os.walk works - only [0] is # referenced if total_list is None: print "Deleting file", fqn # Should do callback.PurgeProcess - left as an exercise :) os.remove(fqn) else: total_list[0] += os.stat(fqn)[stat.ST_SIZE] # and callback to the tool if callback: # for the sake of seeing the progress bar do its thing, # we take longer than we need to... # ACK - for some bizarre reason this screws up the XP # cleanup manager - clues welcome!! :) ## print "Looking in", directory, ", but waiting a while..." ## time.sleep(3) # now do it used = total_list[0] callback.ScanProgress(used, 0, "Looking at " + fqn)
def printHeader(self, file_path): file_len = len(file_path) from stat import ST_SIZE file_size = os.stat(file_path)[ST_SIZE] size_str = utils.formatSize(file_size) size_len = len(size_str) + 5 if file_len + size_len >= self.terminal_width: file_path = "..." + file_path[-(75 - size_len):] file_len = len(file_path) pat_len = self.terminal_width - file_len - size_len printMsg("%s%s%s[ %s ]%s" % (boldText(file_path, c=HEADER_COLOR()), HEADER_COLOR(), " " * pat_len, size_str, Fore.RESET))
def _get_output_for(self, audio_file): from stat import ST_SIZE file_size = os.stat(audio_file.path)[ST_SIZE] return formatSize(file_size)
def printHeader(self, filePath): from stat import ST_SIZE fileSize = os.stat(filePath)[ST_SIZE] size_str = formatSize(fileSize) print("\n%s\t%s[ %s ]%s" % (boldText(os.path.basename(filePath), HEADER_COLOR()), HEADER_COLOR(), size_str, Fore.RESET)) print("-" * 79)
def checkSum(): """ Return a long which can be used to know if any .py files have changed. """ val = 0 for root, dirs, files in os.walk(os.getcwd()): for extension in EXTENSIONS: for f in fnmatch.filter(files, extension): stats = os.stat(os.path.join(root, f)) val += stats[stat.ST_SIZE] + stats[stat.ST_MTIME] return val
def importDF3(self, file, scale=1): try: f = open(file, 'rb'); size = os.stat(file)[stat.ST_SIZE] except: print("Could not open " + file + " for read"); return [] (x, y, z) = struct.unpack(self.__struct2byte3__, f.read(6) ) self.voxel = self.__create__(x, y, z) self.maxX = x self.maxY = y self.maxZ = z size = size-6 if (size == x*y*z): format = 8 elif (size == 2*x*y*z): format = 16 elif (size == 4*x*y*z): format = 32 if (format == 32): for i in range(x*y*z): self.voxel[i] = float(struct.unpack(self.__struct4byte__, f.read(4) )[0]) elif (format == 16): for i in range(x*y*z): self.voxel[i] = float(struct.unpack(self.__struct2byte__, f.read(2) )[0]) elif (format == 8): for i in range(x*y*z): self.voxel[i] = float(struct.unpack(self.__struct1byte__, f.read(1) )[0]) return self #### Local classes not intended for user use
def add_path_info(self, kwargs): ''' for results that are files, supplement the info about the file in the return path with stats about the file path. ''' path = kwargs.get('path', kwargs.get('dest', None)) if path is None: return kwargs b_path = to_bytes(path, errors='surrogate_or_strict') if os.path.exists(b_path): (uid, gid) = self.user_and_group(path) kwargs['uid'] = uid kwargs['gid'] = gid try: user = pwd.getpwuid(uid)[0] except KeyError: user = str(uid) try: group = grp.getgrgid(gid)[0] except KeyError: group = str(gid) kwargs['owner'] = user kwargs['group'] = group st = os.lstat(b_path) kwargs['mode'] = '0%03o' % stat.S_IMODE(st[stat.ST_MODE]) # secontext not yet supported if os.path.islink(b_path): kwargs['state'] = 'link' elif os.path.isdir(b_path): kwargs['state'] = 'directory' elif os.stat(b_path).st_nlink > 1: kwargs['state'] = 'hard' else: kwargs['state'] = 'file' if HAVE_SELINUX and self.selinux_enabled(): kwargs['secontext'] = ':'.join(self.selinux_context(path)) kwargs['size'] = st[stat.ST_SIZE] else: kwargs['state'] = 'absent' return kwargs
def test_seek(self): if verbose: print('create large file via seek (may be sparse file) ...') with self.open(TESTFN, 'wb') as f: f.write(b'z') f.seek(0) f.seek(size) f.write(b'a') f.flush() if verbose: print('check file size with os.fstat') self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
def test_osstat(self): if verbose: print('check file size with os.stat') self.assertEqual(os.stat(TESTFN)[stat.ST_SIZE], size+1)
def get_file_size(path): return os.stat(path)[stat.ST_SIZE]
def getsize(p): """ Return the size of a file, reported by os.stat(). """ st= os.stat(p) return st[stat.ST_SIZE]