質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

2回答

2183閲覧

pythonで、「TypeError: a bytes-like object is required, not 'str' 」が出てしまう

aca_ffk

総合スコア3

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2021/04/19 07:28

編集2021/04/19 07:58

前提・実現したいこと

pythonのライブラリを用いて心理実験課題を作成中、入力データを保存する際にエラーが発生してしまった。

発生している問題・エラーメッセージ

byte型でデータの授受をしているようだが、str型が含まれているため、
~.format()を用いることができないみたいです。

エラーメッセージ Traceback (most recent call last): File "C:\Users\kenjirofukushima\Documents\Python Scripts\assignment5.py", line 141, in <module> datafile.write('{0},{1},{2},{3},{4},{5},{6}\n'.format(*r)) TypeError: a bytes-like object is required, not 'str' ##### Experiment ended. #####

該当のソースコード

python

1# -*- coding: utf-8 -*- 2 3from psychopy import visual, core, event, gui, data, misc 4import numpy, os , random,time,csv 5 6#参加者IDの取得 7try: 8 expInfo = misc.fromFile('lastParams.pickle') 9except: 10 expInfo = {'Participant':'001'} 11 12expInfo['dateStr']=data.getDateStr() 13dlg = gui.DlgFromDict(expInfo, title='Experiment', fixed=['dataStr']) 14if dlg.OK: 15 misc.toFile('lastParams.pickle',expInfo) 16else: 17 core.quit() 18 19#結果の保存場所 20results = [] 21 22 23 24 25colorDic = { 26 u'赤': {'rgb': ( 1, -1,-1), 'type': '1'}, 27 u'黄': {'rgb': ( 1, 1,-1), 'type': '2'}, 28 u'青': {'rgb': (-1, -1, 1), 'type': '3'} 29} 30 31charConditionList = [ 32 {'kanjiChar': u'赤', 'color': u'赤'}, 33 {'kanjiChar': u'黄', 'color': u'赤'}, 34 {'kanjiChar': u'青', 'color': u'赤'}, 35 {'kanjiChar': u'赤', 'color': u'黄'}, 36 {'kanjiChar': u'黄', 'color': u'黄'}, 37 {'kanjiChar': u'青', 'color': u'黄'}, 38 {'kanjiChar': u'赤', 'color': u'青'}, 39 {'kanjiChar': u'黄', 'color': u'青'}, 40 {'kanjiChar': u'青', 'color': u'青'} 41] 42 43text = '今から色のついたもじがでてきます。\n文字の意味ではなく文字の色に基づいて\nボタンをおしてください。\n文字が赤色ならキーボードの1を、\n黄色なら2を、青色なら3をおしてください。\nこの指示が読めたらスペースキーを押してください\n' 44 45myWin = visual.Window(fullscr=True, monitor="Default", allowGUI=False, units="norm", color=(1,1,1)) 46instText = visual.TextStim(myWin,text = text,pos=(0,0),color = (-1,-1,-1),height=0.1) 47 48instText.draw() 49myWin.flip() 50 51keyList = event.waitKeys(keyList=['space']) 52 53#反応時間計測のための設定 54stopwatch = core.Clock() 55 56M=1 57N = len(charConditionList) 58 59for m in range(M): 60 r = list(range(N)) 61 numpy.random.shuffle(r) 62 for i, currentState in enumerate(r): 63 myWin = visual.Window(fullscr=True, monitor="Default", allowGUI=False, units="norm", color=(1,1,1)) 64 charCondition = charConditionList[currentState] 65 colorData = colorDic[charCondition['color']] 66 kanjiCharData = colorDic[charCondition['kanjiChar']] 67 char = charCondition['kanjiChar'] 68 myText = visual.TextStim(myWin,text = char,pos=(0,0),color = colorData['rgb'],height=0.2) 69 myText.draw() 70 myWin.flip() 71 72 #参加者の反応測定開始 73 #前回の刺激提示の影響を消去する 74 event.clearEvents() 75 76 #ストップウォッチをリセット 77 stopwatch.reset() 78 #参加者の反応をリセット 79 Responded = False 80 81 #ストップウォッチをリセットしてからstopwatch.getTime()で測定した時間が一秒を超えるまで以下の処理を実行 82 while stopwatch.getTime() < 1: 83 #もしこれまでに反応がないようなら event.waitKeysで反応を抜き出す 84 #Respondedには反応と反応時間が入る 85 if not Responded: 86 Responded = event.getKeys(keyList=['1','2','3'],timeStamped=stopwatch) 87 88 #もし一秒たっても反応がないならno responseと反応時間なしで処理する 89 if not Responded: 90 Responded = [('no respose', 0)] 91 92 #参加者の測定終了 93 94 95 #正解と不正解のフィードバック 96 if Responded[0][0] == 'no respose': 97 fbText = visual.TextStim(myWin, text = u'無反応',pos=(0,-0.3),color=(-1,-1,-1),height=0.2) 98 rtText = visual.TextStim(myWin, text = str(Responded[0][1])+u'秒',pos=(0,-0.5),color=(-1,-1,-1),height=0.2) 99 #保存用の結果 100 correctIncorrect = None 101 102 elif Responded[0][0] == colorData['type']: 103 fbText = visual.TextStim(myWin, text = u'正解',pos=(0,-0.3),color=(-1,-1,-1),height=0.2) 104 rtText = visual.TextStim(myWin, text = str(Responded[0][1])+u'秒',pos=(0,-0.5),color=(-1,-1,-1),height=0.2) 105 #保存用の結果 106 correctIncorrect = True 107 else: 108 fbText = visual.TextStim(myWin, text = u'不正解',pos=(0,-0.3),color=(-1,-1,-1),height=0.2) 109 rtText = visual.TextStim(myWin, text = str(Responded[0][1])+u'秒',pos=(0,-0.5),color=(-1,-1,-1),height=0.2) 110 #保存用の結果 111 correctIncorrect = False 112 113 #上記で設定したフィードバックと反応時間の書き込み 114 fbText.draw() 115 rtText.draw() 116 117 kanjiCharType = kanjiCharData['type'] 118 colorType = colorData['type'] 119 120 results.append([ 121 N*m + i, 122 kanjiCharType, 123 colorType, 124 colorType==kanjiCharType, 125 Responded[0][0], 126 correctIncorrect, 127 Responded[0][1] 128 ]) 129 130 131 myText = visual.TextStim(myWin,text = u'+',pos=(0,0),color = (-1,-1,-1),height=0.2) 132 myText.draw() 133 myWin.flip() 134 core.wait(0.5) 135 136~~~~~~~~~~~~~~~~~該当箇所~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 137 138curD = os.getcwd() 139datafile = open(os.path.join(curD, 'log', 'Sub{0}_{1}.csv'.format(expInfo['Participant'], 140expInfo['dateStr'])),'wb') 141datafile.write(b'trial, meaning, color, congruent, correct, RT\n') 142for r in results: 143 datafile.write(b'{0},{1},{2},{3},{4},{5},{6}\n'.format(*r)) 144datafile.close() 145 146~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 147

試したこと

https://thinkami.hatenablog.com/entry/2018/12/30/181438
のサイトを参考にし、

datafile.write(b'{0},{1},{2},{3},{4},{5},{6}\n'.format(*r))
の箇所を
datafile.write(b'%a,%a,%a,%a,%a,%a,%a\n'.format(*r))
としてみた。
結果は変わらなかった。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

ファイルを使う方のコードがわかりませんので求めるものかどうかは分かりませんが、

datafile.write(b'{0},{1},{2},{3},{4},{5},{6}\n'.format(*r))

datafile.write('{0},{1},{2},{3},{4},{5},{6}\n'.format(*r).encode())

をすれば、書込みは出来るでしょう。

投稿2021/04/19 08:59

ppaul

総合スコア24666

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

aca_ffk

2021/04/21 05:14

書き込みができました。 ありがとうございました。
guest

0

最初からwで開けば良いのでは?

python

1datafile = open(os.path.join(curD, 'log', 'Sub{0}_{1}.csv'.format(expInfo['Participant'], 2expInfo['dateStr'])),'w') 3datafile.write('trial, meaning, color, congruent, correct, RT\n') 4for r in results: 5 datafile.write('{0},{1},{2},{3},{4},{5},{6}\n'.format(*r)) 6datafile.close()

投稿2021/04/19 08:58

hayataka2049

総合スコア30933

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

aca_ffk

2021/04/21 05:14

ご回答いただきありがとうございます。 こちらでも一度書いてみます。 ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問