-3

How can I get zeros and ones that make a file? For example, how can I open a file with Python and get the zeros and ones that make it up? And convert those zeros and ones again to a file?

Thanks for your help!

  • 2
    If you have a specific issue while solving this yourself you can ask here with your code. – Michael Butscher Aug 13 '21 at 19:22
  • StackOverflow is a site to get help with your code after you've exhausted all research avenues. We're not here tutor you or do your research. – Random Davis Aug 13 '21 at 19:26
  • 1
    Does this answer your question? [How to open and read a binary file in Python?](https://stackoverflow.com/questions/35000687/how-to-open-and-read-a-binary-file-in-python) and then https://stackoverflow.com/questions/8815592/convert-bytes-to-bits-in-python – mkrieger1 Aug 13 '21 at 19:29
  • You should start by trying to use a search engine or follow a Python tutorial. – Karl Knechtel Aug 13 '21 at 19:44

1 Answers1

0

This question is very vague, so I will try and answer some of the possible questions I think you are asking.

How do I open a non-text file in binary mode

Some files need to have the "binary" versions of the files opened. A easier way to think of this would be opening a file in "raw" (binary) vs "plaintext" (text) mode.

Often API's that work with PDF files, and certain other extensions use this to open the files properly since they contain characters that are encoded to be unreadable, and use headers that would garble the files as plain strings.

To do this change the mode of a call to open() to any of these :

  • rb for reading a binary file. The file pointer is placed at the beginning of the file.
  • rb+ reading or writing a binary file
  • wb+ writing a binary file
  • ab+ Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.

For example:


with open("filename.pdf", "rb") as pdf_file:
    ... # Do things

How do I get the binary values of individual string characters

If you are looking to open a file and get a binary association to a character you can use the ord() function combined with the bin() function:

ord("A") # 65
bin(ord("A")) # '0b1000001'

You can then loop through each character of a file and find a binary representation of each letter this way. This is often used in cryptography, like I did for this project.


If neither of those two solve your issues please clarify what you mean in the original question so I can better address it.

Kieran Wood
  • 1,297
  • 8
  • 15