简体   繁体   English

用各种asci码编写python文件

[英]Write python file with various asci codes

I would like to write a python file containing four bytes:我想写一个包含四个字节的 python 文件:

  • A space空间
  • A tab一个选项卡
  • A carriage return回车
  • A newline换行

I'm not able to write it as:我不能把它写成:

open('file.txt', 'w').write(' \t\r\n')

As for whatever reason it's converting the \r into a \n .无论出于何种原因,它将\r转换为\n How would I then write this as the asci codes themselves?然后我将如何将其写为 asci 代码本身? that is:那是:

NEWLINE = 10
CARRIAGE = 13
SPACE = 32
TAB = 9
open('file.txt','wb').write(bytearray([SPACE, TAB, CARRIAGE, NEWLINE]))

Open the file in binary mode and write a byte string.以二进制模式打开文件并写入一个字节串。

open('file.txt', 'wb').write(b' \t\r\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM