\$\begingroup\$
\$\endgroup\$
0
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
3
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
-
2\$\begingroup\$ You probably don't even need to
.strip()
. \$\endgroup\$200_success– 200_success2017年10月08日 14:42:53 +00:00Commented 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\$user3079474– user30794742017年10月08日 17:05:49 +00:00Commented Oct 8, 2017 at 17:05 -
\$\begingroup\$ Yes, true.
int
will discard the end of line. \$\endgroup\$Roman Susi– Roman Susi2017年10月08日 17:36:53 +00:00Commented Oct 8, 2017 at 17:36
lang-py