5967820 on Nostr: ```python """ This script automatically detects whether a given file is encoded in ...
```python
"""
This script automatically detects whether a given file is encoded in base64 or not.
If the file is not in base64, it encodes the file's content into base64 and saves the output
in a new file with the same name plus '.b64' extension. If the file is already in base64,
it decodes it and saves the output in a new file with the original name but without the
'.b64' extension. This process allows for easy encoding and decoding of files to and from
base64 format, making it useful for handling base64 encoded data.
"""
import base64
import os
import sys
def is_base64(sb):
"""
Check if the input is a base64 encoded string or bytes.
Parameters:
- sb (str or bytes): Input to check.
Returns:
- bool: True if input is a valid base64 encoded string/bytes, False otherwise.
"""
try:
if isinstance(sb, str):
# If input is a string, try to decode
sb_bytes = bytes(sb, 'ascii')
elif isinstance(sb, bytes):
# If input is already bytes, use directly
sb_bytes = sb
else:
raise ValueError("The argument must be of type string or bytes.")
# Returns True if re-encoding the decoded bytes matches the original input
return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes
except Exception:
return False
def auto_base64(file_path):
"""
Automatically encodes or decodes a file to/from base64 based on its content.
Parameters:
- file_path (str): Path to the file to encode/decode.
Returns:
- str: Path to the new encoded/decoded file.
"""
with open(file_path, 'rb') as file:
content = file.read()
operation = 'decode' if is_base64(content) else 'encode'
if operation == 'encode':
content_base64 = base64.b64encode(content).decode('utf-8')
output_path = file_path + '.b64'
with open(output_path, 'w') as output_file:
output_file.write(content_base64)
else:
content_decoded = base64.b64decode(content)
output_path = os.path.splitext(file_path)[0]
with open(output_path, 'wb') as output_file:
output_file.write(content_decoded)
return output_path
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: script.py <file_path>")
sys.exit(1)
file_path = sys.argv[1]
new_file_path = auto_base64(file_path)
print(f"Processed file: {new_file_path}")
```
Published at
2024-04-02 19:40:04Event JSON
{
"id": "2ee37081bb496309afe24e4eff38e58d730a1037fbbeec9cdf2cc469fb613bae",
"pubkey": "e12c1dd7fc1e5a6efa017760a3fb3977ee4b7fc519bbcea3e73f13742184b557",
"created_at": 1712086804,
"kind": 1,
"tags": [],
"content": "```python\n\"\"\"\nThis script automatically detects whether a given file is encoded in base64 or not. \nIf the file is not in base64, it encodes the file's content into base64 and saves the output \nin a new file with the same name plus '.b64' extension. If the file is already in base64, \nit decodes it and saves the output in a new file with the original name but without the \n'.b64' extension. This process allows for easy encoding and decoding of files to and from \nbase64 format, making it useful for handling base64 encoded data.\n\"\"\"\n\nimport base64\nimport os\nimport sys\n\ndef is_base64(sb):\n \"\"\"\n Check if the input is a base64 encoded string or bytes.\n\n Parameters:\n - sb (str or bytes): Input to check.\n\n Returns:\n - bool: True if input is a valid base64 encoded string/bytes, False otherwise.\n \"\"\"\n try:\n if isinstance(sb, str):\n # If input is a string, try to decode\n sb_bytes = bytes(sb, 'ascii')\n elif isinstance(sb, bytes):\n # If input is already bytes, use directly\n sb_bytes = sb\n else:\n raise ValueError(\"The argument must be of type string or bytes.\")\n\n # Returns True if re-encoding the decoded bytes matches the original input\n return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes\n except Exception:\n return False\n\ndef auto_base64(file_path):\n \"\"\"\n Automatically encodes or decodes a file to/from base64 based on its content.\n\n Parameters:\n - file_path (str): Path to the file to encode/decode.\n\n Returns:\n - str: Path to the new encoded/decoded file.\n \"\"\"\n with open(file_path, 'rb') as file:\n content = file.read()\n operation = 'decode' if is_base64(content) else 'encode'\n\n if operation == 'encode':\n content_base64 = base64.b64encode(content).decode('utf-8')\n output_path = file_path + '.b64'\n with open(output_path, 'w') as output_file:\n output_file.write(content_base64)\n else:\n content_decoded = base64.b64decode(content)\n output_path = os.path.splitext(file_path)[0]\n with open(output_path, 'wb') as output_file:\n output_file.write(content_decoded)\n\n return output_path\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: script.py \u003cfile_path\u003e\")\n sys.exit(1)\n\n file_path = sys.argv[1]\n new_file_path = auto_base64(file_path)\n print(f\"Processed file: {new_file_path}\")\n```",
"sig": "07c875f141d3ecb4654e3329ec6005cc6f415efc7cae2fc1724fde5e32a7450f20e575266290521c920dd55abc5a668465117630a5d7f3c38fc8f8328d351284"
}