问题描述
源代码:
def create_results_file(self):
self.prog_file = os.path.join(self.mydir, 'training_progress.csv')
data_file = open(self.prog_file, 'wb')
data_file.write('epoch,mean_score,mean_q_val\n')
data_file.close()
self.term_prob_file = os.path.join(self.mydir, 'term_prob.csv')
data_file = open(self.term_prob_file, 'wb')
data_file.write('epoch,termination_prob\n')
data_file.close()
错误:
TypeError: a bytes-like object is required, not 'str'
解决方案
参考了https://blog.csdn.net/qq_40723932/article/details/127288023中提到的解决方法:
1. str转bytes
第一种:在str类型前加b,即b"str"
第二种:在str后加.encode("utf-8"),即str.encode("utf-8"),编码方式默认是utf-8,里面的"utf- 8"可以省略,下同。
2. bytes转str
只有一种方法:在bytes后加.decode("utf-8"),即bytes.encode("utf-8")
将代码改为:
def create_results_file(self):
self.prog_file = os.path.join(self.mydir, 'training_progress.csv')
data_file = open(self.prog_file, 'wb')
data_file.write(b'epoch,mean_score,mean_q_val\n')
data_file.close()
self.term_prob_file = os.path.join(self.mydir, 'term_prob.csv')
data_file = open(self.term_prob_file, 'wb')
data_file.write(b'epoch,termination_prob\n')
data_file.close()
问题解决。