本文整理汇总了Python中os.SEEK_END属性的典型用法代码示例。如果您正苦于以下问题:Python os.SEEK_END属性的具体用法?Python os.SEEK_END怎么用?Python os.SEEK_END使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类os
的用法示例。
在下文中一共展示了os.SEEK_END属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __write_trx_image
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def __write_trx_image(self,ambit_fw_file):
logger=self.logger
logger.LOG_DEBUG("Writing TRX image to %s" % self.mtd_file)
ambit_header=AmbitHeaderFromFile(ambit_fw_file,logger=logger)
#Need room for TRX image + 4-byte trx image size + 4-byte checksum
if (self.mtd_size - 8) < ambit_header.trx_img_size:
raise Exception("TRX image is too large for mtd size of: %d" % self.mtd_size)
ambit_fw=open(ambit_fw_file,"rb")
ambit_fw.seek(ambit_header.trx_img_off)
trx_data=ambit_fw.read()
mtd_fh=open(self.mtd_file,"r+b")
self.__mtd_write_data(mtd_fh,trx_data)
logger.LOG_DEBUG("Done writing TRX image.")
mtd_fh.seek(-8,os.SEEK_END)
logger.LOG_DEBUG("Writing footer to %s" % self.mtd_file)
logger.LOG_DEBUG("Writing trx image size.")
mtd_fh.write(ambit_header.packed_trx_img_size())
logger.LOG_DEBUG("Writing trx checksum.")
mtd_fh.write(ambit_header.packed_trx_checksum())
mtd_fh.close()
logger.LOG_INFO("Done writing TRX image to %s" % self.mtd_file)
示例2: seek
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def seek(self, pos, whence=os.SEEK_SET):
"""Seek to a position in the file.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
if whence == os.SEEK_SET:
self.position = min(max(pos, 0), self.size)
elif whence == os.SEEK_CUR:
if pos < 0:
self.position = max(self.position + pos, 0)
else:
self.position = min(self.position + pos, self.size)
elif whence == os.SEEK_END:
self.position = max(min(self.size + pos, self.size), 0)
else:
raise ValueError("Invalid argument")
self.buffer = b""
self.fileobj.seek(self.position)
示例3: get_latest_saved_article_id
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def get_latest_saved_article_id() -> int:
"""이미 저장한 가장 최근 글번호를 가져오기. 저장된 글이 없으면 0을 반환"""
# 글이 없으면 0
if not os.path.isfile(CSV_WHOLE):
return 0
# 파일 끝 부분에서 몇 줄 읽어온 뒤 마지막 줄의 첫 칼럼(article_id) 반환
with open(CSV_WHOLE, 'rb') as f:
# 마지막 줄을 빠르게 찾기 위해 "거의" 끝 부분으로 이동
f.seek(0, os.SEEK_END)
f.seek(-min([f.tell(), 1024 * 100]), os.SEEK_CUR)
# 마지막 줄에서 article id 추출
last_line = f.readlines()[-1].decode('utf-8')
article_id = int(last_line.split(',')[0])
return article_id
示例4: test_read_truncated_header_raises_error
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def test_read_truncated_header_raises_error(self, data, count, encoding, random):
written_headers = data.draw(extended_textual_header(count=count))
with BytesIO() as fh:
for header in written_headers:
for line in header:
fh.write(line.encode(encoding))
fh.seek(0, os.SEEK_END)
length = fh.tell()
truncate_pos = random.randrange(0, length - 1)
truncated_buffer = fh.getbuffer()[:truncate_pos]
with BytesIO(truncated_buffer):
with raises(EOFError):
toolkit.read_extended_headers_counted(fh, count, encoding=encoding)
del truncated_buffer
示例5: seek
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def seek(self, pos, whence=os.SEEK_SET):
"""Seek to a position in the file.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
if whence == os.SEEK_SET:
self.position = min(max(pos, 0), self.size)
elif whence == os.SEEK_CUR:
if pos < 0:
self.position = max(self.position + pos, 0)
else:
self.position = min(self.position + pos, self.size)
elif whence == os.SEEK_END:
self.position = max(min(self.size + pos, self.size), 0)
else:
raise ValueError("Invalid argument")
self.buffer = ""
self.fileobj.seek(self.position)
示例6: _get_trailing_bytes
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def _get_trailing_bytes(self, filepath, remaining_bytes):
try:
# Read trailing_bytes from the end of `filepath`. Even if
# `filepath` is corrupt, its final bytes may be fine and the first
# piece of the next file can be saved.
_debug(f'reader: Seeking to {-remaining_bytes} in {os.path.basename(filepath)}')
with open(filepath, 'rb') as f:
f.seek(-remaining_bytes, os.SEEK_END)
trailing_bytes = f.read(remaining_bytes)
_debug(f'reader: Read {len(trailing_bytes)} trailing bytes '
f'from {os.path.basename(filepath)}: {_pretty_bytes(trailing_bytes)}')
except OSError:
# Fake trailing_bytes with padding bytes to maintain piece offsets.
trailing_bytes = b'\x00' * remaining_bytes
_debug(f'reader: Reading from {os.path.basename(filepath)} failed, pretending to have read '
f'{len(trailing_bytes)} trailing bytes: {_pretty_bytes(trailing_bytes)}')
return trailing_bytes
示例7: __putUploadFile
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def __putUploadFile(self, url, tmp):
# Determine file length outself and add a "Content-Length" header. This
# used to work in Python 3.5 automatically but was removed later.
tmp.seek(0, os.SEEK_END)
length = str(tmp.tell())
tmp.seek(0)
connection = self._getConnection()
connection.request("PUT", url, tmp, headers={ 'Content-Length' : length,
'If-None-Match' : '*', 'User-Agent' : 'BobBuildTool/{}'.format(BOB_VERSION) })
response = connection.getresponse()
response.read()
if response.status == 412:
# precondition failed -> lost race with other upload
raise ArtifactExistsError()
elif response.status not in [200, 201, 204]:
raise ArtifactUploadError("PUT {} {}".format(response.status, response.reason))
示例8: create_media
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def create_media(media):
"""Download media link"""
if is_valid_url(media.data_value):
filename = media.data_value.split('/')[-1]
data_file = NamedTemporaryFile()
content_type = mimetypes.guess_type(filename)
with closing(requests.get(media.data_value, stream=True)) as r:
for chunk in r.iter_content(chunk_size=CHUNK_SIZE):
if chunk:
data_file.write(chunk)
data_file.seek(os.SEEK_SET, os.SEEK_END)
size = os.path.getsize(data_file.name)
data_file.seek(os.SEEK_SET)
media.data_value = filename
media.data_file = InMemoryUploadedFile(
data_file, 'data_file', filename, content_type,
size, charset=None)
return media
return None
示例9: get_last_line_from_file
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def get_last_line_from_file(file):
# concerns to address(may be much later):
# how will last line lookup work with log rotation when a new file is created?
#- will that new file be empty at any time? or will it have a partial line from the previous file?
line = None
if os.stat(file).st_size < 5000:
# quick hack to handle files with one line
with open(file, 'r') as f:
for line in f:
pass
else:
# optimized for large log files
with open(file, 'rb') as f:
f.seek(-2, os.SEEK_END)
while f.read(1) != b'\n':
f.seek(-2, os.SEEK_CUR)
line = f.readline().decode()
return line
示例10: sidesum
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def sidesum(filename, chksize, bufsize, offset=0):
if bufsize < chksize:
bufsizes = (bufsize, chksize % bufsize)
else:
bufsizes = (chksize, 0)
offset = abs(offset)
with readopen(filename, sequential=False, direct=True) as (read, fd):
whence = (offset, os.SEEK_SET)
header = _chunksum(fd, read, chksize, bufsizes, whence)
whence = (-chksize - offset, os.SEEK_END)
footer = _chunksum(fd, read, chksize, bufsizes, whence)
return header, footer
示例11: _open_logcat_file
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def _open_logcat_file(self):
"""Create a file object that points to the beginning of the logcat file.
Wait for the logcat file to be created by the subprocess if it doesn't
exist.
"""
if not self._adb_logcat_file_obj:
start_time = time.time()
while not os.path.exists(self.adb_logcat_file_path):
if time.time() > start_time + CREATE_LOGCAT_FILE_TIMEOUT_SEC:
raise Error(
self._ad,
'Timeout while waiting for logcat file to be created.')
time.sleep(1)
self._adb_logcat_file_obj = io.open(
self.adb_logcat_file_path, 'r', encoding='utf-8',
errors='replace')
self._adb_logcat_file_obj.seek(0, os.SEEK_END)
示例12: read_from_handle_truncated
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def read_from_handle_truncated(file_handle, max_len):
"""Read from file handle, limiting output to |max_len| by removing output in
the middle."""
file_handle.seek(0, os.SEEK_END)
file_size = file_handle.tell()
file_handle.seek(0, os.SEEK_SET)
if file_size <= max_len:
return file_handle.read()
# Read first and last |half_max_len| bytes.
half_max_len = max_len // 2
start = file_handle.read(half_max_len)
file_handle.seek(file_size - half_max_len, os.SEEK_SET)
end = file_handle.read(half_max_len)
truncated_marker = b'\n...truncated %d bytes...\n' % (file_size - max_len)
return start + truncated_marker + end
示例13: get_abbrv_string_from_file
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def get_abbrv_string_from_file(self, filename):
if not os.path.exists(filename):
return "Can't read from " + filename + " because it doesn't exist."
with open(filename, 'r', encoding="utf-8", errors='replace') as f:
if os.path.getsize(filename) > 10000:
retstring = f.read(4000)
retstring += "\n\nSNIP SNIP SNIP (leaving out some of the output!)\n\n"
# f.seek(-4000, os.SEEK_END)
f.seek(os.path.getsize(filename)-4000)
retstring += f.read(4000)
else:
retstring = f.read()
return retstring
# http://stackoverflow.com/questions/800197/
示例14: parse
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def parse(self, fp):
try:
# The basic file format:
# HEADER
# object...
# refid->offset...
# TRAILER
self._fp = fp
self._fp.seek(-32, os.SEEK_END)
trailer = self._fp.read(32)
if len(trailer) != 32:
raise InvalidFileException()
(
offset_size, self._ref_size, num_objects, top_object,
offset_table_offset
) = struct.unpack('>6xBBQQQ', trailer)
self._fp.seek(offset_table_offset)
self._object_offsets = self._read_ints(num_objects, offset_size)
self._objects = [_undefined] * num_objects
return self._read_object(top_object)
except (OSError, IndexError, struct.error, OverflowError,
UnicodeDecodeError):
raise InvalidFileException()
示例15: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import SEEK_END [as 别名]
def __init__(self, file_path, offset=0, sector_size=512):
"""Provide a file like object of a volume inside a disk image.
Args:
file_path: String, denoting the file path to the disk image.
offset: An offset in bytes to the volume within the disk.
sector_size: The size in bytes of a single sector, defaults to 512.
"""
self._block_size = 0
self._offset_start = 0
self._orig_offset = offset
ofs = int(offset / sector_size)
self._block_size, self._image_size = GetImageSize(file_path, ofs)
self._fh = open(file_path, 'rb')
self._fh.seek(0, os.SEEK_END)
self._fh_size = self._fh.tell()
self._image_offset = ofs
if self._block_size:
self._offset_start = self._image_offset * self._block_size
self._fh.seek(self._offset_start, 0)