前提
Pythonでindex_labelの振り直しをしたい
実現したいこと
- それぞれのデータに対して新たにラベル番号を振り直したいです
apple1.json
apple2.json
banana1.json
banana2.json
banana3.json
orange1.json
...
これらのファイルの中にそれぞれ”index_label:〇”と番号が振られているのですが、
元のデータから一部をピックアップして使用したいため、このラベル番号の値を振り直したいです。
また、ラベル番号はapple1とapple2は同じ番号(index_label:1)、banana1とbanana2.とbanana3は(index_label:2)同じ番号というような仕様にしたいです。
ファイル自体の書き換えを行うコードは出てくるのですが、具体的にどのような命令を書けばいいかアドバイスをいただきたいです。
よろしくお願いいたします。
追記
返信欄のコードでは、ファイル名が直接代入されていました。
以下、ファイル名のリストを代入するコードに変更しましたが、同様のエラーが出ています。
Python
1import os 2 3with open('E:/VI/list.txt') as f: 4 file_readlines = f.readlines() 5 6str =file_readlines 7 8 9if str.startswith('apple'): 10 path = 'E:/VI' 11 f = open(path) 12 data_lines = data_lines.replace("label_index: 5", "label_index: 1") 13 14 f.close()
追記2
Python
1import os 2 3with open('E:/VI/list.txt') as f: 4 file_readlines = f.readlines() 5 6for json_file in file_readlines: 7 if json_file.startswith('apple'): 8 path = 'E:/VI' + json_file 9 f = open(path) 10 data_lines = data_lines.replace("label_index: 5", "label_index: 1") 11 f.close()
回答をもとに書き換えましたが、上記の認識で合っているでしょうか。
このコードで実行したところInvalid argumentとエラーが出てしまいました。(’E:/VI/apple001.json’)
しかし、ファイルを開いて確認したところ"label_index: 0"に書き換えられていました。
追記3
Python
1import os 2 3with open('E:/VI/list.txt') as f: 4 file_readlines = f.readlines() 5 6for json_file in file_readlines: 7 if json_file.startswith('apple'): 8 path = 'E:/VI' + json_file 9 with open(path) as reader: #Invalid argument 10 content = reader.read() 11 12 content = content.replace("label_index: 5", "label_index: 1") 13 14 with open(path) as writer: 15 writer.write(content)
回答をもとにf = openからのコードを変更してみました。
相変わらずpath部分にInvalid argumentエラーが出てしまいます。
追記4
Python
1import os 2 3with open('E:/VI/list.txt') as f: 4 file_readlines = f.readlines() 5 6for json_file in file_readlines: 7 if json_file.startswith('apple'): 8 path = 'E:/VI/' + json_file 9 with open(path, mode="w") as reader: #Invalid argument 10 content = reader.read() 11 12 content = content.replace("label_index: 5", "label_index: 1") 13 14 with open('1apple.json', mode="w") as writer: 15 writer.write(content)
新しくファイルを作成して書き込むようコードを変更してみました。
「E:/VI/」に変更してみたもののInvalid argumentのままでした。
試しに、
Python
1print(path)
を実行したところ、
E:/VI/apple-001.json
E:/VI/apple-002.json
E:/VI/apple-003.json
E:/VI/apple-004.json
E:/VI/apple-005.json
が出力されたため、ファイルは確かにあるのですが、上手くいきません。