Home > front end >  For loop only returns first line of textfile
For loop only returns first line of textfile

Time:10-04

I am trying to make a program where i have to check if certain numbers are in use in a text file. The problem is that my for loop only loops trough the first line, instead of every line. How can i solve this? I've already used readlines() but that has not worked for me. This is the code and i've got a text file with: 1;, 2; and 3;, each on a seporated line. Hope someone can help!

if int(keuze) == 2:
    def new_safe():
        with open('fa_kluizen.txt', 'r') as f:
            for number in f:
                return number

    print(new_safe())

My text File:

# TextFile
    1;
    2;
    3;

CodePudding user response:

You are returning too early (at first iteration).

You can read all lines in a list while cleaning the data and then return that list.

with open('fa_kluizen.txt', 'r') as f:
    data = [line.strip() for line in f]
return data

Also most of the time its bad to create a function inside an if-statement. Maybe you can add a little bit more information about what you want to achieve.

CodePudding user response:

you are returning the first line you encounter, and by doing so, the program exits the current function and of course, the loop.

One way to do it is:

def new_safe():
    with open('fa_kluizen.txt', 'r') as f:
        return f.read().splitlines()

Which returns a each line as a list of the strings.

Output:

['1;', '2;', '3;']

CodePudding user response:

That's beacause "return numbrer", Try

if int(keuze) == 2:
    def new_safe():
        my_list = []
        with open('fa_kluizen.txt', 'r') as f:
            for number in f:
                my_list.append(number)
        return my_list

  • Related