I have a text in a file in my directory. I want to convert it into bytes. How can I do it with Python3?
Asked
Active
Viewed 1.4k times
3
-
1Just open it as a binary file, in the call to `open` use the options string `'rb'`. – Paul Rooney Jun 25 '17 at 04:06
-
Alrighty !! @Paul..and if I want to copy its content to other file?? – user7083361 Jun 25 '17 at 04:07
-
1don't bother opening it, in that case just copy it using `shutil` or another applicable module. – Paul Rooney Jun 25 '17 at 04:12
-
Thanks @Paul..can I decode it into a string again after opening it in 'rb' – user7083361 Jun 25 '17 at 04:13
-
Sure see [here](https://stackoverflow.com/questions/606191/convert-bytes-to-a-python-string). – Paul Rooney Jun 25 '17 at 04:16
-
@Paul..could you write the code here for me to understand.. I'm a Python amateur.. Thanks a lot – user7083361 Jun 25 '17 at 06:12
1 Answers
2
Assuming your file is named filename.ext
and you are running in the parent directory of dir
, then you could try the following code:
with open('dir/filename.ext', 'rb') as f:
contents = f.read()
# Do something with contents
If all you want is to copy the file, then you could do this:
import shutil
shutil.copyfile('dir/filename.txt', 'dir/copiedfile.txt')
This will create a copiedfile.txt
in the dir
directory.

Ébe Isaac
- 11,563
- 17
- 64
- 97