Please let me know because the code has been created in Sikulix.
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)
LINE= FIN.READLINE ()
line= file_data [i] .Strip ()
for I in Range (3):When
with 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 file
OPENThe internal cursor of the row to be read at the same time is initialized to the first line.
To read one line
OPENAfter that, each line in for statement
※ In this case, multiple times in FOR statement
ReadLineDo 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)
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 library
(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 ())
- python : The sum of the square when the sum of integers is 0
- Domain information acquisition may fail in Python
- python : Even if you specify a file name with TO_CSV FilenotfoundError
- python : How to Remove Multiple Rows of NUMPY NDARRAY
- About the IF's Except Exception Error in the Python Try block
- python : To extract the list value in the list
- How do I output an average calculation using a While loop at Python?
- python : Sending an infrared light with IRRP.py extends doubled
- python : "FilenotFoundError: [Errno 2] No Such File or Directory: Tell me how to deal with 'data /sample.csv' '