本文整理汇总了Python中io.FileIO类的典型用法代码示例。如果您正苦于以下问题:Python FileIO类的具体用法?Python FileIO怎么用?Python FileIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FileIO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, name, mode="rb", buffering=0):
"""file(name[, mode[, buffering]]) -> file object
Open a file. The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending. The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing. Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size. The preferred way
to open a file is with the builtin open() function.
Add a 'U' to mode to open the file for input with universal newline
support. Any line ending in the input file will be seen as a '\n'
in Python. Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.
'U' cannot be combined with 'w' or '+' mode.
"""
if six.PY2:
FileIO.__init__(self, name, mode, buffering)
else: # for python3 we drop buffering
FileIO.__init__(self, name, mode)
self.lock = _Semaphore()
self.__size = None
示例2: __init__
def __init__(self, path, flags, info, fh=None, base='.', depth=0):
super(File, self).__init__()
self.path = path
self.flags = flags
self.fh = fh
self.info = info
self.depth = depth
self.cursor = 0
self.offset = 0
self.state = File.HEADER
# stream item info
self.stream_offset = 0
self.zip_header = b''
self.descriptor = b''
# data file info
self.data = None
self.data_name = ''
self.data_len = 0
# streams
prefix = os.path.join(base, 'meta', os.path.basename(path))
self.stream = FileIO(prefix + '.stream', 'rb')
self.dir = FileIO(prefix + '.dir', 'rb')
self.data_dir = os.path.join(base, 'data')
# init
self._load_stream_item()
self.lock = threading.Lock()
示例3: get_from_file_memory_duplicate
def get_from_file_memory_duplicate(path):
io = FileIO(path,'rb')
io2 = StringIO()
io2.write(io.read())
io.close()
io2.seek(0, os.SEEK_SET)
return ELF(io2)
示例4: wrapper
def wrapper(self, file_, *args, **kwargs):
if isinstance(file_, basestring):
# Using FileIO here instead of open()
# to be able to override the filename
# which is later used when uploading the file.
#
# Explanation:
#
# 1) Restkit reads the filename
# from "name" attribute of a file-like object,
# there is no other way to specify a filename;
#
# 2) The attribute may contain the full path to file,
# which does not work well as a filename;
#
# 3) The attribute is readonly when using open(),
# unlike FileIO object.
file_ = FileIO(file_, 'rb')
file_.name = path.basename(file_.name)
if hasattr(file_, 'read'):
# A file-like object must have 'read' method
return fn(self, file_, *args, **kwargs)
else:
raise TypeError('Expected either a string '
'containing a path to file or a '
'file-like object, got {}'.format(type(file_)))
示例5: FileRestoreResponse
class FileRestoreResponse(RestoreResponse):
BODY_TAG_SUFFIX = "-body"
EXTENSION = "xml"
def __init__(self, username=None, items=False):
super(FileRestoreResponse, self).__init__(username, items)
self.filename = os.path.join(settings.SHARED_DRIVE_CONF.restore_dir, uuid4().hex)
self.response_body = FileIO(self.get_filename(self.BODY_TAG_SUFFIX), "w+")
def get_filename(self, suffix=None):
return "{filename}{suffix}.{ext}".format(filename=self.filename, suffix=suffix or "", ext=self.EXTENSION)
def __add__(self, other):
if not isinstance(other, FileRestoreResponse):
raise NotImplemented()
response = FileRestoreResponse(self.username, self.items)
response.num_items = self.num_items + other.num_items
self.response_body.seek(0)
other.response_body.seek(0)
shutil.copyfileobj(self.response_body, response.response_body)
shutil.copyfileobj(other.response_body, response.response_body)
return response
def finalize(self):
"""
Creates the final file with start and ending tag
"""
with open(self.get_filename(), "w") as response:
# Add 1 to num_items to account for message element
items = self.items_template.format(self.num_items + 1) if self.items else ""
response.write(
self.start_tag_template.format(
items=items, username=self.username, nature=ResponseNature.OTA_RESTORE_SUCCESS
)
)
self.response_body.seek(0)
shutil.copyfileobj(self.response_body, response)
response.write(self.closing_tag)
self.finalized = True
self.close()
def get_cache_payload(self, full=False):
return {"data": self.get_filename() if not full else open(self.get_filename(), "r")}
def as_string(self):
with open(self.get_filename(), "r") as f:
return f.read()
def get_http_response(self):
headers = {"Content-Length": os.path.getsize(self.get_filename())}
return stream_response(open(self.get_filename(), "r"), headers)
示例6: flipByteAt
def flipByteAt(inputfile, position):
"""Flips the bits for the byte at the specified position in the input file."""
f = FileIO(inputfile, "r+")
f.seek(position)
byte = ord(f.read(1))
f.seek(-1, 1) # go back 1 byte from current position
f.write(struct.pack("B", byte^0xFF)) # read in the byte and XOR it
f.close()
示例7: write_to_file
def write_to_file(file_fd: io.FileIO, dir_fileno: Optional[int],
data: bytes, fsync: bool=True):
length_to_write = len(data)
written = 0
while written < length_to_write:
written = file_fd.write(data[written:])
if fsync:
fsync_file_and_dir(file_fd.fileno(), dir_fileno)
示例8: HidrawDS4Device
class HidrawDS4Device(DS4Device):
def __init__(self, name, addr, type, hidraw_device, event_device):
try:
self.report_fd = os.open(hidraw_device, os.O_RDWR | os.O_NONBLOCK)
self.fd = FileIO(self.report_fd, "rb+", closefd=False)
self.input_device = InputDevice(event_device)
self.input_device.grab()
except (OSError, IOError) as err:
raise DeviceError(err)
self.buf = bytearray(self.report_size)
super(HidrawDS4Device, self).__init__(name, addr, type)
def read_report(self):
try:
ret = self.fd.readinto(self.buf)
except IOError:
return
# Disconnection
if ret == 0:
return
# Invalid report size or id, just ignore it
if ret < self.report_size or self.buf[0] != self.valid_report_id:
return False
if self.type == "bluetooth":
# Cut off bluetooth data
buf = zero_copy_slice(self.buf, 2)
else:
buf = self.buf
return self.parse_report(buf)
def read_feature_report(self, report_id, size):
op = HIDIOCGFEATURE(size + 1)
buf = bytearray(size + 1)
buf[0] = report_id
return fcntl.ioctl(self.fd, op, bytes(buf))
def write_report(self, report_id, data):
if self.type == "bluetooth":
# TODO: Add a check for a kernel that supports writing
# output reports when such a kernel has been released.
return
hid = bytearray((report_id,))
self.fd.write(hid + data)
def close(self):
try:
self.fd.close()
self.input_device.ungrab()
except IOError:
pass
示例9: save_q
def save_q(Q, file_location):
"""Saves the current q learning values to the specified location."""
try:
makedirs(dirname(file_location))
except OSError as exc:
pass
file = FileIO(file_location, 'w')
pickle.dump(Q, file)
file.close()
示例10: close
def close(self):
name = self.name
FileIO.close(self)
if self.__temporary:
try:
os.unlink(name)
except Exception as err:
logger.error("Unable to remove %s: %s" % (name, err))
raise(err)
示例11: bench_file_write55
def bench_file_write55():
f = FileIO(tmpf.name, "r+")
zblk = b"\x55" * blksize
for i in xrange(filesize // blksize):
pos = 0
while pos < blksize:
n = f.write(memoryview(zblk)[pos:])
assert n != 0
pos += n
f.close()
示例12: get_contents_to_file
def get_contents_to_file(self, key, filepath_to_store_to, *, progress_callback=None):
fileobj = FileIO(filepath_to_store_to, mode="wb")
done = False
metadata = {}
try:
metadata = self.get_contents_to_fileobj(key, fileobj, progress_callback=progress_callback)
done = True
finally:
fileobj.close()
if not done:
os.unlink(filepath_to_store_to)
return metadata
示例13: read_from_file
def read_from_file(file_fd: io.FileIO, start: int, stop: int) -> bytes:
length = stop - start
assert length >= 0
file_fd.seek(start)
data = bytes()
while file_fd.tell() < stop:
read_data = file_fd.read(stop - file_fd.tell())
if read_data == b'':
raise ReachedEndOfFile('Read until the end of file')
data += read_data
assert len(data) == length
return data
示例14: flipBitAt
def flipBitAt(inputfile, position):
"""Flips the bit at the specified position in the input file."""
if not 0<=position<(8*os.path.getsize(inputfile)):
raise IndexError("Position "+str(position)+" is out of range")
f = FileIO(inputfile, "r+")
f.seek(position/8)
byte = ord(f.read(1))
f.seek(-1, 1) # go back 1 byte from the current position
bitnum = position%8
f.write(struct.pack("B", byte^(1<<(7-bitnum))))
f.close()
示例15: _bench_file_read
def _bench_file_read(hasher, expect):
f = FileIO(tmpf.name, "r")
b = bytearray(blksize)
h = hasher()
while 1:
n = f.readinto(b)
if n == 0:
break
h.update(xbuffer(b, 0, n)) # NOTE b[:n] does copy
f.close()
assert h.digest() == expect