Home >Backend Development >Python Tutorial >Python loops don't work with readlines()

Python loops don't work with readlines()

王林
王林forward
2024-02-06 09:54:04634browse

Python 循环不适用于 readlines()

Question content

It should calculate "---------------------- --" number of lines, but it doesn't work, also using print("test") doesn't show up in the console, it always returns 0. But for example the line print("hi") works. The program just doesn't see my loop and I don't know why. :(

def check_id():
    with open('data.txt', 'r') as f:
        lines = f.readlines()
        ad = 0
                print("hi")  # this line works
        for i in lines:
            print("test")  # this line doesn't work
            if i == "-------------------------":
                ad += 1

        return str(ad)

If I need to send the complete code to solve the problem, please ask

I changed the mode "a" to "r" so that it reads the rows correctly, and it does, but I still can't check the array to get the number of rows. If you have any guesses or solutions, please write them down.

EDIT: Here is the complete code for my data.py and the text in the file data.txt

from datetime import date
date = date.today()


def write_note(line):
    with open('data.txt', 'a') as f:
        if line == "!quit":
            f.write('\n')
            f.write("-------------------------")
            f.write('\n')
            ad = check_id()
            f.write(ad)
            f.write('\n')
            f.write("________________________")
            f.write('\n')
        else:
            f.write(line)
            f.write("\n")


def read_note(id):
    with open('data.txt', 'r') as f:
        pass


def see_all():
    with open('data.txt', 'r') as f:
        get_lines = f.readlines()
        for i in get_lines:
            print(i)
        return get_lines


def del_note(ad):
    with open('data.txt', 'a') as f:
        pass


def logs():
    pass


def check_id():
    with open('data.txt', 'r') as f:
        ad = 0
        for i in f:
            if i == "-------------------------":
                ad += 1

        return str(ad)

Now it is txt file:

fugy
hello
hai
bebra

-------------------------
0
________________________
uha
imna
fsjfoe
geso;rsevdn

-------------------------
0  # This one
________________________

I'm trying to make a notebook so I can write notes and read them. Delete func I will do it later. The idea is to make this zero bigger every time you add an annotation.


Correct Answer


I think the problem is with your data.txt file (probably empty as you mentioned "test" is not visible in the console, which means that the script is not run inside a for loop, in other words: lines the length of the iterator is zero).

I have written a working code, you can see the code and test file with the script output below.

Code:

def check_id():
    with open('data.txt', 'r') as opened_file:
        ad = 0
        print("hi")  # this line works
        for i in opened_file:
            print("test")  # this line doesn't work
            if i == "-------------------------":
                ad += 1
        return str(ad)


result = check_id()
print(f"result: {result}")
Contents of

data.txt:

test_1
-------------------------
test_2
-------------------------
test_3
-------------------------
test_4

test:

> python3 test.py 
hi
test
test
test
test
test
test
test
result: 0

edit:

op shared the complete source code and used data.txt which contains cr lf characters (Details about the character ). This means that these rows must be striped using the rstrip method.

In this case, only the check_id function is relevant, so I only share the modified function:

def check_id():
    with open('data.txt', 'r') as f:
        ad = 0
        for i in f:
            # The cr and lf characters should be removed from line. Please see the above reference for details.
            if i.rstrip() == "-------------------------":
                ad += 1
        return str(ad)


result = check_id()
print(result). # Result is 4

The above is the detailed content of Python loops don't work with readlines(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete