Python os.open() 方法
2020-04-29 本文已影响0人
桑鱼nicoo
语法
os.open(file, flags[, mode]);
参数
-
filename 要打开的文件名
-
flags 以下常量是标志的选项:
- os.O_RDONLY -仅供读取使用
- os.O_WRONLY - 仅供写入
- os.O_RDWR - 开放阅读和写作
- os.O_NONBLOCK - 不要阻止打开
- os.O_APPEND - 附加在每次写入
- os.O_CREAT - 如果不存在,则创建文件
-
返回新打开的文件的文件描述符
示例
# 打开文件
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())
写入成功
