简体   繁体   中英

Python read and store each line of file in a separate variable of your choice without multiple "with open" calls

As mentioned in the Question title, I have below script that reads an(in the code below <authfile> is just a placeholder which can contain any secure auth file like Git) and stores the inner lines as credentials into separate variables of User's choice:

import itertools

with open('.<authfile>', 'r') as <authfile>:
    gist_id = next(itertools.islice(<authfile>, 0, None)).rstrip('\n')
with open('.<authfile>', 'r') as <authfile>:
    token = next(itertools.islice(<authfile>, 1, None)).rstrip('\n')

But as you see in code, there's bit of non-performance as I have to use 2 with open calls for getting separate lines by number and storing into variables.

My sample data file as I try to read looks quite like below, but the order of gist_ids may change , token I will keep it at last as much as possible, so you see it's better in my case to read this file just by specific line numbers, still open to suggestions for managing this file:

<gist_id1>
<gist_id2>
<gist_id4>
....
....
....
<token>

How can I make this a performant script which fires single with open call and still stores each line(without newline) into a separate variable? Also how can I do this with minimal code-change?

If you're just fetching the first two lines, you don't need anything more than:

with open('.<authfile>', 'r') as authfile:
    gist_id = authfile.readline().rstrip()
    token = authfile.readline().rstrip()

Don't know if my answer here qualifies for minimal code change or not, but I was able to figure out the way to have any specific line to be read from file and store it in separate variables also of my wish.

With inspiration and ideas from Tim Roberts I got it working without using itertools module and just adding another method for proper enumeration. Below is my answer:

def get_lines(fp, line_numbers):
    return (x for i, x in enumerate(fp) if i in line_numbers)
with open('.<authfile>', 'r') as <authfile>:
    lines = get_lines(<authfile>, [0,1])
    lines = list(lines)
    gist_id = lines[0].rstrip()
    token = lines[1].rstrip()

Note: I can specify any line to be read by adding it in this array [0,1] like [0,1,5,7,9] .

Please comment here if anyone needs further explanation of this answer.

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