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.

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Oct 8, 2017 at 8:59
\$\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.

answered Oct 8, 2017 at 13:56
\$\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\$ Commented Oct 8, 2017 at 17:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.