Home>

Please let me know because the code has been created in Sikulix.
Program beginners.

I'm thinking of reading one line of text data three times, but this code only reads the first line three times.
When this is the second repetition, only the second line is to be able to read only the third line, but it is a soubt that you should add anything.
Could you lend me wisdom? Thank you.

with open ("text.txt", "R") AS F:
    file_data= f.readlines ()
for I in Range (3):
    with open ("text.txt") AS FIN:
        LINE= FIN.READLINE ()
        PRINT (LINE)
        LINE= FIN.READLINE ()
  • Answer # 1

    You can load the desired row with the following changes. (Sample Code 2)

    before change:LINE= FIN.READLINE ()
    After change:line= file_data [i] .Strip ()

    orfor I in Range (3):Whenwith open ("text.txt") AS FIN:It is also possible to replace the line of (Sample Code 1)

    READLINEThen, one row reads and the internal cursor moves to the next line, but the fileOPENThe internal cursor of the row to be read at the same time is initialized to the first line.
    To read one lineOPENAfter that, each line in for statementReadLineto hold.
    ※ In this case, multiple times in FOR statementReadLineDo not call

    There is no problem in either method, but personally it wants to close as soon as you open the file, so the former (sample code 2) is like.

    # 1.FOR Method to read each line in order before reading the text before turning the statement
    with open ("text.txt", "R") AS F:
        for I in Range (3):
            LINE= F.Readline (). Strip ()
            PRINT (LINE)
    # 2. How to read any row from file_data already loaded with all lines
    with open ("text.txt", "R") AS F:
        file_data= f.readlines ()
    for I in Range (3):
        line= file_data [i] .Strip ()
        PRINT (LINE)
    # 3. How to read text every time you turn the statement and read only any row
    for I in Range (3):
        with open ("text.txt", "R") AS F:
            line= f.readlines () [i] .Strip ()
            PRINT (LINE)
    
    

    Thank you! We adopted the second method. Thank you very much for helping me!

    tom2021-07-21 20:16:09
  • Answer # 2

    or less str.splitlinesIt is a way to use ITERATION.

    with open ('text.txt') AS F:
      for line in f.read (). Splitlines () [: 3]:
        PRINT (LINE)
    
    
                                
                            
  • Answer # 3

    For Python's standard librarylinecachethere is.
    (However, please note that the amount saved if the file size is large)

    Reference: (docs.python.org/en) Linecache ---Random access to text line

    (hereinafter, it can operate with CoLAB)

    Import Linecache
    fname= 'SAMPLE_DATA /README.MD'
    Print (lineCache.getLine (FName, 1) .rstrip ())
    print (lineCache.getLine (Fname, 5) .rstrip ())
    print (Linecache.getLine (Fname, 4) .rstrip ())