This is what I have:
When I try to do this, it shows me an error: IndexError: list index out of range
Could someone help?

with open(os.path.join(path, file.replace(".root", ".txt")), 'r') as f:
    lines = f.readlines()
htemp = TH1D(name, name, nBins, eMin, eMax)
for i in range(len(lines)):
    htemp.SetBinContent(i + 1, float(lines[i]))
entries = int(lines[-1])
return prepareHisto(htemp, xLabel, yLabel), entries

Dani AI

Generated

Quick diagnosis and actionable fixes.

The traceback shows the code is trying to read a “last” line from an empty sequence of lines — that happens when the text file yields no usable lines. Common causes are a wrong filename/path, an empty file, or a file containing only blank lines. As suggested, start by checking that the file actually exists and contains data; below is a defensive parsing pattern that both verifies the file and avoids indexing into an empty list.

import os

txt_path = os.path.join(path, os.path.splitext(file)[0] + '.txt')

if not os.path.exists(txt_path):
    raise FileNotFoundError("Missing file: " + txt_path)
if os.path.getsize(txt_path) == 0:
    raise ValueError("Empty file: " + txt_path)

with open(txt_path, 'r') as f:
    lines = [ln.strip() for ln in f if ln.strip()]  # drop blank lines

if not lines:
    raise ValueError("No data lines in " + txt_path)

entries_line = lines.pop()            # take final summary line safely
try:
    entries = int(entries_line)
except ValueError:
    raise ValueError("Final line is not an integer: " + entries_line)

for i, item in enumerate(lines, start=1):
    try:
        value = float(item)
    except ValueError:
        raise ValueError("Non-numeric value on data line {}: {}".format(i, item))
    if i > nBins:
        break
    htemp.SetBinContent(i, value)

Extra notes: use os.path.splitext instead of simple string replace to avoid bad filenames; filter out blank lines before assuming the last line is the entries count; and decide whether to raise an error or clamp if the number of data lines doesn't match nBins. Adding clear error messages (including the filename and offending line) makes debugging far quicker.

Recommended Answers

All 3 Replies

Normally, the exception traceback that python prints on the screen tells you the line number and statement where the error occurred. Can you post the whole traceback ?

I don't know if this would help you to understand!

Traceback (most recent call last):
  File "Desktop/python/check2.py", line 135, in readTextIntoHistogram
    entries = int(lines[-1])
IndexError: list index out of range

If there is no lines[-1] it means that the lines list is empty (there is no last item). Try to check the length of the list first.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.