### Check stream existence with olefile.OleFileIO.exists() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Checks for the existence of streams or storages using olefile.OleFileIO.exists(). The path is case-insensitive. The example checks for 'worddocument' and then for 'macros/vba'. ```default if ole.exists('worddocument'): print("This is a Word document.") if ole.exists('macros/vba'): print("This document seems to contain VBA macros.") ``` -------------------------------- ### Get creation and modification timestamps with getctime() and getmtime() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Returns creation and modification timestamps as Python datetime objects with UTC timezone. Returns None if timestamps are not present. The methods are case-insensitive. ```default c = ole.getctime('WordDocument') m = ole.getmtime('WordDocument') ``` -------------------------------- ### Get root storage timestamps via OleFileIO.root attribute Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Gets creation and modification timestamps of the root storage using the root attribute. Returns None if timestamps are not present. ```default c = ole.root.getctime() m = ole.root.getmtime() ``` -------------------------------- ### Get stream size with olefile.OleFileIO.get_size() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Returns the size of a stream in bytes. The method is case-insensitive. ```default s = ole.get_size('WordDocument') ``` -------------------------------- ### Parse user-defined properties with olefile.OleFileIO.get_userdefined_properties() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Parses streams containing user-defined properties (new in v0.47). The returned list contains dictionaries with 'property_name' and 'value' keys; the example prints each variable's index, name, and value. ```default variables = ole.get_userdefined_properties(streamname, convert_time=True) if len(variables): for index, variable in enumerate(variables): print('\t{} {}: {}'.format(index, variable['property_name'],variable['value'])) ``` -------------------------------- ### Test if a file is an OLE container with isOleFile Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Check if a file is an OLE container using isOleFile(). Returns True if the file starts with the OLE magic, False otherwise. The first argument can be a file path (bytes or unicode string smaller than 1536 bytes) or a file-like object. ```python if olefile.isOleFile('myfile.doc'): # open the file with OleFileIO else: sys.exit('Not an OLE file') ``` -------------------------------- ### Get stream type with olefile.OleFileIO.get_type() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Returns the type of a stream/storage as one of the constants: olefile.STGTY_STREAM, olefile.STGTY_STORAGE, olefile.STGTY_ROOT, or False for a non-existing path. The method is case-insensitive. ```default t = ole.get_type('WordDocument') ``` -------------------------------- ### Parse a property stream with olefile.OleFileIO.getproperties() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Parses a property stream not handled by get_metadata, returning a dictionary indexed by integer property IDs. For example, in the standard '\x05SummaryInformation' stream, property #2 is the document title and #3 is the subject. ```default p = ole.getproperties('specialprops') ``` -------------------------------- ### Sample output of ole.listdir() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Sample output of ole.listdir() for a Word document, showing the list of streams and storages. Note the line breaks and commas as they appear in the source. ```default [['\x01CompObj'], ['\x05DocumentSummaryInformation'], ['\x05SummaryInformation'] , ['1Table'], ['Macros', 'PROJECT'], ['Macros', 'PROJECTwm'], ['Macros', 'VBA', 'Module1'], ['Macros', 'VBA', 'ThisDocument'], ['Macros', 'VBA', '_VBA_PROJECT'] , ['Macros', 'VBA', 'dir'], ['ObjectPool'], ['WordDocument']] ``` -------------------------------- ### List all streams with olefile.OleFileIO.listdir() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Prints the list of all streams and storages in the OLE file, as returned by olefile.OleFileIO.listdir(). Each stream is represented as a list of path components. ```default print(ole.listdir()) ``` -------------------------------- ### List only storages with olefile.OleFileIO.listdir() options Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Calls olefile.OleFileIO.listdir() with options to list only storages (streams=False, storages=True). This option is new in v0.26. ```default ole.listdir (streams=False, storages=True) ``` -------------------------------- ### Run olefile as a script to display OLE file structure Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Use this command to display the structure and metadata of an OLE file. Add -c to check that all streams can be read fully, -d for very verbose debugging information, and -l debug to display debugging messages. ```default olefile.py myfile.doc ``` -------------------------------- ### Import olefile Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Import the olefile module to use its functions and classes. ```python import olefile ``` -------------------------------- ### Open OLE file from disk Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Creates an OleFileIO object from a file path. This is the basic way to open an OLE file from disk. ```default ole = olefile.OleFileIO('myfile.doc') ``` -------------------------------- ### Read stream data with olefile.OleFileIO.openstream() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Opens the 'Pictures' stream from a PPT file using olefile.OleFileIO.openstream() and reads its data. The returned object is an instance of olefile.OleStream, based on io.BytesIO, with data stored in memory. ```default pics = ole.openstream('Pictures') data = pics.read() ``` -------------------------------- ### Open OLE file in write mode with write_mode=True Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Open an OLE file in read/write mode by passing write_mode=True to olefile.OleFileIO. This is required before using write features. The write features are new (v0.40) and not thoroughly tested. ```python ole = olefile.OleFileIO('test.doc', write_mode=True) ``` -------------------------------- ### Open OLE file from file-like object Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Opens an OLE file from a file-like object. The first block works when the object has read, seek, and tell methods. If the object lacks seek or tell, read the entire file into a bytes string before parsing, as shown in the second block. ```default ole = olefile.OleFileIO(f) ``` ```default data = f.read() ole = olefile.OleFileIO(data) ``` -------------------------------- ### Open OLE file with context manager Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Recommended way to open an OLE file since v0.46. Using the context manager guarantees the OleFileIO object is closed when exiting the with block, even if an exception is triggered. It calls olefile.OleFileIO.close() automatically. ```default with olefile.OleFileIO('myfile.doc') as ole # perform all operations on the ole object ``` -------------------------------- ### Generate debugging output with olefile.py -d -c Source: https://github.com/decalage2/olefile/blob/master/doc/Contribute.rst Run olefile with debug output and check integrity, redirecting the output to debug.txt for issue reporting. ```default olefile.py -d -c file >debug.txt ``` -------------------------------- ### Test a file in memory with isOleFile data argument Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Test a file in memory using the data argument with a bytes string containing the file. This is available since v0.47. ```python if olefile.isOleFile(data=file_in_memory): # open the file with OleFileIO ``` -------------------------------- ### Open OLE file with strict defect handling Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Tells the parser to be more strict and raise exceptions for files that do not fully conform to OLE specifications. By default the parser is permissive and only raises exceptions for fatal errors. The raise_defect option is new in v0.14. ```default ole = olefile.OleFileIO('myfile.doc', raise_defects=olefile.DEFECT_INCORRECT) ``` -------------------------------- ### Overwrite a sector with olefile.OleFileIO.write_sect() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Overwrites any sector of the file. Data smaller than the sector size is padded with null characters. Sector 0 is the second sector; use -1 to write the first sector. ```default ole.write_sect(0x17, b'TEST') ``` -------------------------------- ### olefile.OleFileIO.get_metadata() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Extracts metadata from standard property streams in an OLE file and returns an OleMetadata object. ```APIDOC ## [READ] olefile.OleFileIO.get_metadata() ### Description Checks if standard property streams exist, parses all the properties they contain, and returns an `olefile.OleFileIO.OleMetadata` object with the found properties as attributes. Available since v0.24. ### Method READ ### Endpoint olefile.OleFileIO.get_metadata() ### Parameters No parameters. ### Request Example ```python meta = ole.get_metadata() print('Author:', meta.author) print('Title:', meta.title) print('Creation date:', meta.create_time) # print all metadata: meta.dump() ``` ### Response #### Success Response (200) - **OleMetadata object** (object) - Contains metadata attributes such as author, title, create_time, etc. #### Response Example ```python meta = ole.get_metadata() ``` ``` -------------------------------- ### Available OleMetadata attributes Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Lists the available attributes on the OleMetadata object returned by get_metadata(). These attributes correspond to properties parsed from standard property streams. ```python codepage, title, subject, author, keywords, comments, template, last_saved_by, revision_number, total_edit_time, last_printed, create_time, last_saved_time, num_pages, num_words, num_chars, thumbnail, creating_application, security, codepage_doc, category, presentation_target, bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips, scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty, chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed, version, dig_sig, content_type, content_status, language, doc_version ``` -------------------------------- ### OLE File Stream/Storage Information and Sector Overwrite Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Methods to retrieve stream/storage information and overwrite sectors in OLE files. ```APIDOC ## olefile.OleFileIO.get_size() ### Description Returns the size of a stream in bytes. ### Method `get_size()` ### Parameters - **name** (str) - Required - Path of the stream. ### Returns - **int** - Size of the stream in bytes. ### Example ```python s = ole.get_size('WordDocument') ``` ``` ```APIDOC ## olefile.OleFileIO.get_type() ### Description Returns the type of a stream/storage. ### Method `get_type()` ### Parameters - **name** (str) - Required - Path of the stream/storage. ### Returns - **int or False** - One of `olefile.STGTY_STREAM`, `olefile.STGTY_STORAGE`, `olefile.STGTY_ROOT`, or `False` if the path does not exist. ### Example ```python t = ole.get_type('WordDocument') ``` ``` ```APIDOC ## olefile.OleFileIO.getctime() ### Description Returns the creation timestamp of a stream/storage as a Python datetime object with UTC timezone. Returns `None` if not present. ### Method `getctime()` ### Parameters - **name** (str) - Required - Path of the stream/storage. ### Returns - **datetime or None** - Creation timestamp, or `None` if not stored. ### Example ```python c = ole.getctime('WordDocument') ``` ``` ```APIDOC ## olefile.OleFileIO.getmtime() ### Description Returns the modification timestamp of a stream/storage as a Python datetime object with UTC timezone. Returns `None` if not present. ### Method `getmtime()` ### Parameters - **name** (str) - Required - Path of the stream/storage. ### Returns - **datetime or None** - Modification timestamp, or `None` if not stored. ### Example ```python m = ole.getmtime('WordDocument') ``` ``` ```APIDOC ## olefile.OleFileIO.root.getctime() ### Description Returns the creation timestamp of the root storage as a Python datetime object with UTC timezone. Returns `None` if not present. ### Method `getctime()` ### Parameters None. ### Returns - **datetime or None** - Creation timestamp, or `None` if not stored. ### Example ```python c = ole.root.getctime() ``` ``` ```APIDOC ## olefile.OleFileIO.root.getmtime() ### Description Returns the modification timestamp of the root storage as a Python datetime object with UTC timezone. Returns `None` if not present. ### Method `getmtime()` ### Parameters None. ### Returns - **datetime or None** - Modification timestamp, or `None` if not stored. ### Example ```python m = ole.root.getmtime() ``` ``` ```APIDOC ## olefile.OleFileIO.write_sect() ### Description Overwrites any sector of the file. If the provided data is smaller than the sector size (normally 512 bytes, sometimes 4KB), data is padded with null characters. ### Method `write_sect()` ### Parameters - **sect** (int) - Required - Sector index. Note: sector 0 is actually the second sector of the file; use -1 to write the first sector. - **data** (bytes) - Required - Data to write. ### Returns None. ### Example ```python ole.write_sect(0x17, b'TEST') ``` ``` -------------------------------- ### olefile.OleFileIO.get_userdefined_properties() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Parses streams containing user-defined properties. Returns a list of dictionaries, each containing 'property_name' and 'value' keys. Supports optional conversion of timestamp properties. ```APIDOC ## olefile.OleFileIO.get_userdefined_properties() ### Description Parses streams containing user-defined properties. Returns a list of dictionaries, each containing 'property_name' and 'value' keys. Supports optional conversion of timestamp properties. ### Method GET ### Endpoint olefile.OleFileIO.get_userdefined_properties(streamname, convert_time=False) ### Parameters #### Path Parameters - **streamname** (string) - Required - The name of the stream containing user-defined properties. #### Query Parameters - **convert_time** (boolean) - Optional - If True, timestamp properties are converted to Python datetime objects (UTC timezone). Default is False. ### Request Example ```python variables = ole.get_userdefined_properties(streamname, convert_time=True) ``` ### Response #### Success Response (200) - **variables** (list) - List of dictionaries, each with 'property_name' and 'value' keys. #### Response Example ```python variables = ole.get_userdefined_properties(streamname, convert_time=True) if len(variables): for index, variable in enumerate(variables): print('\t{} {}: {}'.format(index, variable['property_name'], variable['value'])) ``` ``` -------------------------------- ### olefile.OleFileIO.getproperties() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Parses any property stream not handled by get_metadata. Returns a dictionary indexed by integers, where each integer is the property index pointing to its value. Supports optional conversion of timestamp properties to Python datetime objects and exclusion of specific properties from conversion. ```APIDOC ## olefile.OleFileIO.getproperties() ### Description Parses any property stream that is not handled by get_metadata. Returns a dictionary indexed by integers, where each integer is the property index pointing to its value. For example, in the standard property stream '\x05SummaryInformation', the document title is property #2 and the subject is #3. ### Method GET ### Endpoint olefile.OleFileIO.getproperties(streamname, convert_time=False, no_conversion=None) ### Parameters #### Path Parameters - **streamname** (string) - Required - The name of the property stream to parse. #### Query Parameters - **convert_time** (boolean) - Optional - If True, timestamp properties are converted to Python datetime objects (UTC timezone). Default is False, which converts timestamps to number of seconds since Jan 1, 1601. - **no_conversion** (list of integers) - Optional - List of property indexes that should not be converted even if convert_time is True. For example, total editing time in '\x05SummaryInformation' is property #10. ### Request Example ```python p = ole.getproperties('specialprops') ``` ### Response #### Success Response (200) - **dictionary** (dict) - Dictionary indexed by integers, each integer is the property index pointing to its value. #### Response Example ```python p = ole.getproperties('specialprops', convert_time=True, no_conversion=[10]) ``` ``` -------------------------------- ### olefile.OleFileIO.write_stream() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Overwrites an existing stream in an OLE file with new data of the same size. ```APIDOC ## [WRITE] olefile.OleFileIO.write_stream() ### Description Overwrites an existing stream in the OLE file with new data. The new data must be exactly the same size as the existing stream; resizing is not supported. Works on streams of any size (stored in the main FAT or the MiniFAT) since v0.45. ### Method WRITE ### Endpoint olefile.OleFileIO.write_stream(stream_name, data) ### Parameters #### Path Parameters - **stream_name** (string) - Required - Name of the stream to overwrite. #### Request Body - **data** (bytes) - Required - New data for the stream, must be the same size as the existing stream. ### Request Example ```python ole = olefile.OleFileIO('test.doc', write_mode=True) data = ole.openstream('WordDocument').read() data = data.replace(b'foo', b'bar') ole.write_stream('WordDocument', data) ole.close() ``` ### Response #### Success Response (200) No return value. #### Response Example No response body. ``` -------------------------------- ### Extract metadata with olefile.get_metadata() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Extracts standard property streams and returns an OleMetadata object with attributes like author, title, and create_time. Available since v0.24. ```python meta = ole.get_metadata() print('Author:', meta.author) print('Title:', meta.title) print('Creation date:', meta.create_time) # print all metadata: meta.dump() ``` -------------------------------- ### Convert between slash path and list path Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Convert a slash-separated path string to a list of path components and vice versa. The slash syntax is easier but may fail if a name contains a slash; the list syntax works in all cases. ```python slash_path = '/'.join(list_path) list_path = slash_path.split('/') ``` -------------------------------- ### Open OLE file from bytes string Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Opens an OLE file from a bytes string. The size of the string determines if it is treated as a file path or file content: strings larger than 1535 bytes are expected to contain an OLE file, otherwise they are treated as file paths. New in v0.41. ```default ole = olefile.OleFileIO(s) ``` -------------------------------- ### olefile.OleFileIO.close() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Closes the OleFileIO object and the underlying file on disk. Should be called after parsing to release the file handle. ```APIDOC ## olefile.OleFileIO.close() ### Description Closes the OleFileIO object and the underlying file on disk. Should be called after parsing to release the file handle. ### Method GET ### Endpoint olefile.OleFileIO.close() ### Parameters None ### Request Example ```python ole.close() ``` ### Response #### Success Response (200) No return value. ``` -------------------------------- ### Close the OLE file with ole.close() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Closes the OleFileIO object to release the underlying file. Required for applications that process multiple OLE files; simple scripts that terminate immediately may omit it. (new in v0.22) ```default ole.close() ``` -------------------------------- ### Print parsing issues Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Prints the list of non-fatal issues detected during parsing, available in the olefile.OleFileIO.parsing_issues attribute (new in 0.25). Iterates over the list and prints each exception type and message, or 'None' if no issues. ```default print('Non-fatal issues raised during parsing:') if ole.parsing_issues: for exctype, msg in ole.parsing_issues: print('- %s: %s' % (exctype.__name__, msg)) else: print('None') ``` -------------------------------- ### Overwrite a stream with olefile.write_stream() Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Overwrites an existing stream in an OLE file. The new data must be exactly the same size as the existing stream; changing the size is not supported. Works on streams of any size since v0.45. ```python ole = olefile.OleFileIO('test.doc', write_mode=True) data = ole.openstream('WordDocument').read() data = data.replace(b'foo', b'bar') ole.write_stream('WordDocument', data) ole.close() ``` -------------------------------- ### Parse property stream with convert_time and no_conversion options Source: https://github.com/decalage2/olefile/blob/master/doc/Howto.rst Parses a property stream with timestamp conversion to Python datetime objects (UTC). The no_conversion parameter (new in v0.25) accepts a list of property indexes to leave unconverted, such as total editing time in '\x05SummaryInformation'. ```default p = ole.getproperties('specialprops', convert_time=True, no_conversion=[10]) ```