3

I have a text in a file in my directory. I want to convert it into bytes. How can I do it with Python3?

user7083361
  • 33
  • 1
  • 1
  • 6

1 Answers1

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