os.open(file, flags[, mode]);
# 打开文件
fd = os.open("/Users/pengyapan/PycharmProjects/Practise/os/haha.py", os.O_RDWR | os.O_CREAT)
# 写入字符串
ret = os.write(fd, "print(\"hello world\")")
但是上面代码在运行时出现了错误:TypeError: a bytes-like object is required, not 'str'
解决方法:通过encode()将要写入的字符串转为bytes
# 打开文件
fd = os.open("/Users/pengyapan/PycharmProjects/Practise/os/haha.py", os.O_RDWR | os.O_CREAT)
# 写入字符串
ret = os.write(fd, "print(\"hello world\")".encode())
写入成功