Skip to content Skip to sidebar Skip to footer

Writing To Files In Ascii With Python3, Not Utf8

I have a program that I created with two sections. The first one copies a text file with an integer in the middle of the file name in this format. file = 'Filename' + 'str(int)'

Solution 1:

This is an example of writing to a file in ASCII. You need to open the file in byte mode, and using the .encode method for strings is a convenient way to get the end result you want.

s = '12345'ascii = s.encode('ascii')
withopen('somefile', 'wb') as f:
    f.write(ascii)

You can obviously also open in rb+ (read and write byte mode) in your case if the file already exists.

withopen('somefile', 'rb+') as f:
    existing = f.read()
    f.write(b'ascii without encoding!')

You can also just pass string literals with the b prefix, and they will be encoded with ascii as shown in the second example.

Post a Comment for "Writing To Files In Ascii With Python3, Not Utf8"