[Python] Is this the correct way to move to the beginning of each line in a text file using...

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    from sys import argv
    script, input_file = argv

    hello = open(input_file)

    read1 = hello.readline()

    print("Line1: ", read1, end = "")
    line1 = len(read1) + 1
    print(line1)

    read2 = hello.readline()

    print("Line2: ", read2, end = "")
    line2 = len(read1 + read2) + 2
    print(line2)

    read3 = hello.readline()

    print("Line3: ", read3, end = "")
    line3 = len(read1 + read2 + read3) + 3
    print(line3)

    read4 = hello.readline()
    print("Line4: ", read4)


    beep = input("""I give you the option to choose the line you print:
    1. Type: first line
    2. Type: second line
    3. Type: third line
    4. Type: fourth line
    """)

    if (beep == "first line"):
    choice = 0
    elif (beep == "second line"):
    choice = line1
    elif (beep == "third line"):
    choice = line2
    else:
    choice = line3

    def runner(f):
    hello.seek(f)
    green = hello.readline()
    print("The line reads: ", green)

    runner(choice)


    I want to print a particular line from a text file as specified by the user. What I know is that the seek() function takes input in terms of bytes to move the reading pointer at the position corresponding to the size in bytes. Like if a text file has 4 lines and each line is 10 bytes in size (including the newline character) then the size input 11 corresponds to the beginning of the second line. Now if I want to move the reading position to the beginning of the fourth line I will input 31 (sum of sizes of previous lines + 1) to the seek() function to move the reading/writing pointer to the fourth line. But in the attached piece of code I have input sum of the sizes of previous 3 lines + 3 to get the position of the beginning of the fourth line (instead of sum of sizes of previous 3 lines + 1, which makes more sense), but still the code runs perfectly fine. In fact when I replace the +3 (or +2) by +1, I do not get the required line printed.

    enter image description here`

    Continue reading...

Compartilhe esta Página