Python loops don't work with readlines()

王林
Release: 2024-02-06 09:54:04
forward
590 people have browsed it

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)
Copy after login

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)
Copy after login

Now it is txt file:

fugy
hello
hai
bebra

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

-------------------------
0  # This one
________________________
Copy after login

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}")
Copy after login
Contents of

data.txt:

test_1
-------------------------
test_2
-------------------------
test_3
-------------------------
test_4
Copy after login

test:

> python3 test.py 
hi
test
test
test
test
test
test
test
result: 0
Copy after login

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
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template