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\$
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\$
  • 2
    \$\begingroup\$ You probably don't even need to .strip(). \$\endgroup\$ – 200_success Oct 8 '17 at 14:42
  • 1
    \$\begingroup\$ Since there is only one ID per line, there is no need to use the .strip() \$\endgroup\$ – user3079474 Oct 8 '17 at 17:05
  • \$\begingroup\$ Yes, true. int will discard the end of line. \$\endgroup\$ – Roman Susi Oct 8 '17 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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