0

I have a file that has the filename a new line, then the hashvalue of the file then a newline. This pattern repeats. Example:

blah.txt
23847EABF8742
file2.txt
1982834E387FA

I have a class called 'information' that has two member variables.

class information:
     filename=''
     hashvalue=''

Now I want to read in the file and store a filename and hashvalue in a new instance of an 'information' object and then push the instance of the information object onto a list.

The problem I am having is iterating over the file to read it. I want to read it line by line until the end of file. The problem with python's 'for line in file' method is that it grabs a line each time and I would be forced to do some kind of every other tactic to put the data in the correct member variable.

Instead, this is what I am trying to do...

list=[]
while(not end of file)
    x = information()
    x.filename = file.readline()
    x.hashvalue = file.readline()
    list.append(x)
0

4 Answers 4

2

You could write a generator function:

def twolines(file):
    cur = None
    for i in file:
        if cur is None:
            cur = i
        else:
            yield (cur, i)
            cur = None

Then pass your file object to twolines(), and do something like

for i, j in twolines(file):
    x = information()
    x.filename, x.hashvalue = i,j
    list.append(x)
Sign up to request clarification or add additional context in comments.

Comments

1
while True:
    x = information()
    x.filename = file.readline()
    if not x.filename:
       break
    x.hashvalue = file.readline()
    my_list.append(x)

maybe?

or

while True:
    x = information()
    try:
        x.filename = next(file)
        x.hashvalue = next(file)
    except StopIterationError:
        break
    my_list.append(x)

or my favorite

my_list = [filename,hashvalue for filename,hashvalue in zip(file,file)]

Comments

0

Another simple fix is by counting the lines. Introduce a variable like line = 0 for this. now you could try the following:

for lines in file:
    line = line + 1
    if line  % 2 == 1:
        # This will be the filename
    else:
        # This will be the hashcode

1 Comment

Im pretty sure he explicitly stated he didnt want to do that ... also for i,line in enumerate(file): if i%2 would probably be a minor improvement
0

How about this:

list = [information(filename=x.rstrip(), hashvalue=next(it).rstrip()) for x in file]

3 Comments

file is already an iter ... you can just do for x in file.. and use next(file) instead of next(x)
it = iter(file.readlines()) is exactly identical to it=file
try and run it ... set file="A B C".split()

Your Answer

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.