SlickNutz SlickNutz - 3 months ago 8
Python Question

Python List Iterate Trouble

I'm having a very hard time figuring out I'm doing wrong running my python script in Windows to get the expected result.

I have a directory with list1.txt, list2.txt, list3.txt, list4.txt, and list5.txt. Each list contains separate line strings that are unique such as list1.txt will have item1, item2, item3, item4, and item5 each as values on separate lines. Then list2.txt will have item6-item10 on separate lines and so on.

What I need to do is to say, for each text file in this directory, list each value in list1 until done, then list each value in list2, then list3, and so on until you finish the last list.

Here is a link to the image of my results with notes: https://i.imgur.com/YBxQUqi.png

The code I have it below but the results are not what I'm expecting and I'm having an extremly hard time determining what I'm doing wrong here.

def my_range(start, end, step):
while start <= end:
yield start
start += step

for x in my_range(1, 5, 1):
import os
rootdir = os.getcwd()
fis = rootdir + "\list\list" + str(x) + ".txt"
files = open(fis,'rU')
lines = files.readlines()
print(lines)
print(fis)
for line in lines:
print("Item = " + line)


I need the results to read from every file in the lists.txt file and from every value in each file rather than just the last file. I think I'm not doing the for loop correctly nesting wise and I just cannot figure it out. I also tested with passing arguments to a function and defining a function to do this and I totally hosed up the script trying that.

Please anyone help me when you can with this problem I cannot figure out and just pulling my hair out of head.

Answer

Your second for loop needs to be a sub-loop of the primary one. Also, do not import os each time you loop through, just do it once. Your code should look like this:

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step
import os
for x in my_range(1, 5, 1):
    rootdir = os.getcwd()
    fis = rootdir + "\list\list" + str(x) + ".txt"
    files = open(fis,'rU')
    lines = files.readlines()
    print(lines)
    print(fis)
    for line in lines:
        print("Item = " + line)

But, I would comment that you should instead use a with open(fid,'rU') as f: approach as that will release the file from being locked if the code errors out or crashes. Then you could just do something like this:

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step
import os
for x in my_range(1, 5, 1):
    rootdir = os.getcwd()
    fis = rootdir + "\list\list" + str(x) + ".txt"
    with open(fis,'rU') as files:
        print(fis)
        for line in files:
            print("Item = " + line)