简体   繁体   中英

python: read a file on each line and store only ints into list

I read a file which looks like this:

1
2
3
4

Then I read this lines into list:

['1\n', '2\n', '3\n', '4']

My question is, how and what is the best way to get ints and store them into list, without any strings or this '\\n'?

You can do it as:

with open(filename, 'r') as f:
    nums = [int(i.strip()) for i in f.readlines()]

>>> print nums
[1,2,3,4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM