2
\$\begingroup\$

I want to read a list of IDs (as integers) from a file in Python3. The file has a single ID per line and no blank lines.

with open(file_eval_id) as f:
    eval_ids = [list(map(int, line.split()))[0] for line in f]

Is there a cleaner way of doing it? I have doubts about referencing the list(...)[0] as the best way.

\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

You can use something like the following:

with open(file_eval_id) as f:
    eval_ids = [int(line) for line in f]

The code assumes, that ID is the only thing in the line.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ You probably don't even need to .strip(). \$\endgroup\$ Commented Oct 8, 2017 at 14:42
  • 1
    \$\begingroup\$ Since there is only one ID per line, there is no need to use the .strip() \$\endgroup\$ Commented Oct 8, 2017 at 17:05
  • \$\begingroup\$ Yes, true. int will discard the end of line. \$\endgroup\$
    – Roman Susi
    Commented Oct 8, 2017 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.