我想將文本文檔中的行分割成數組,並將屬性附加到數組中的每個值,然後將它們轉換爲json以顯示在文本中文件。列表索引超出範圍python in for循環
然而,無論我如何調整我的代碼,我還是遇到錯誤「 IndexError:列表索引響電子商務」爲fields1 [1]行。
with open(fileName,'r') as file:
for line in file:
if line.startswith('-') and 'section1' in line:
for li in file:
fields1 = li.split(',')
testarr.append({
"section1a": fields1[0],
"section1b": fields1[1],
"section1c": fields1[2]
})
with open(test_dir,'a+') as test_file:
json.dump(testarr, test_file)
問題出在哪裏?
你能在這裏提供輸入文件內容? –
2011-12-05 11:30:00,54321,12345 上面的行是輸入的一個示例。有3列,所以技術上[2]字段仍然應該工作@SainathBatthala – decemberrobot
此外,我添加了所有3列的打印聲明,它能夠打印所有3個字段,但我不知道爲什麼我不能附加它。 – decemberrobot