操作系统ftruncate()在执行时显示了一些错误,例如TypeError:需要一个byteslike对象

2024-10-01 17:35:13 发布

您现在位置:Python中文网/ 问答频道 /正文

import os,sys

sr=os.open("sri.txt",os.O_RDWR|os.O_CREAT)

os.write(sr,"This is the test-This is test")

os.ftruncate(sr,10)

os.lseek(sr,0,0)

str=os.read(sr,100)

print("Read string is:",str)

os.close(sr)

print("closed the file successfully!!")

Tags: thetestimporttxtisossysopen
1条回答
网友
1楼 · 发布于 2024-10-01 17:35:13

在python3中,所有字符串都自动使用Unicode。你知道吗

所以我可以找到两种方法来解决它。你知道吗

一种是在写入字符串之前附加“b”,如下所示。你知道吗

os.write(sr,b"This is the test-This is test")

或者

另一个是call encode(),如下所示。你知道吗

str = "This is the test-This is test"

ret = os.write(sr,str.encode())

为了更好地理解python3中的字符串行为,请参阅下面的教程

http://pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/

相关问题 更多 >

    热门问题