Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Read and Convert a Binary File to CSV in Python?
1
How to Read and Convert a Binary File to CSV in Python?

5/5 – (1 vote)

To read a binary file, use the
Code:
open('rb')
function within a context manager (
Code:
with
keyword) and read its content into a string variable using
Code:
f.readlines()
. You can then convert the string to a CSV using various approaches such as the
Code:
csv
module.

Here’s an example to read the binary file
Code:
'my_file.man'
into your Python script:

Code:
with open('my_file.man', 'rb') as f: content = f.readlines() print(content)

Per default, Python’s built-in
Code:
open()
function opens a text file. If you want to open a binary file, you need to add the
Code:
'b'
character to the optional
Code:
mode
string argument.
  • To open a file for reading in binary format, use
    Code:
    mode='rb'
    .

  • To open a file for writing in binary format, use
    Code:
    mode='rb'
    .

Now that the content is in your Python script, you can convert it to a CSV using the various methods outlined in this article:

[Image: 1f30d.png] Learn More: Convert a String to CSV in Python

After you’ve converted the data to the comma-separated values (CSV) format demanded by your application, you can write the string to a file using either the
Code:
print()
function with file argument or the standard
Code:
file.write()
approach.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: