[Tutor] Using 'with open' statementfor reading a file two lines at a time

dn PyTutor at DancesWithMice.info
Thu Nov 26 23:05:18 EST 2020


> I am using 'with open' statement to read a file two lines at a time and then combining them together to print the results into another file. I can read the first two lines, combine them and print the result into another file and then that is it. Just the first and second lines were printed and save.
> 
> How can I continue reading the third and fourth lines and so forth on until the end of the file?


> # Daily Three Pick Three 99 Combine Test py
> # 11/26/2020
> import sys

Why import the sys library?
Where is it used in the code?


> filename1 = "Pick_Three_Drawings_File.txt"
> filename2 = "Pick_Three_Drawings_File_Combine.txt"
> file1 = open(filename1, "r")
> file2 = open(filename2, "w")

The two files are now open (assuming no run-time exception).
So, on the next line, it is not necessary to open file1 again! *


> with open(filename1) as file1:

Am wondering if you are thinking that the with (Context Manager) has 
some looping function?
It doesn't.

>      line1 = file1.readline().strip()
>      line2 = file1.readline().strip()
>      line3 = (line1 + line2)

Given that there is only a concatenation operation there is no need for 
the parentheses (which indicate which operation(s) should have priority 
execution).
The same applies on the next line, given that the usual left-to-right 
'priority' is applicable.

>      line4 = (line3[ 0: 4] + line3[ 4: 6] + line3[ 6: 8] + line3[ 8: 9] 
> + line3[ 9:12] + line3[20:21] + line3[21:24])

The specification didn't mention this, beyond "combining".
Why not:

	line4 = line3[ :12 ] + line3[ 20:24 ]


>      file2.write(line4)
> file1.close()
> file2.close()


So, to answer the question:
- create a loop using a while statement to replace the with
- set the while-condition to True, ie an infinite loop
- wrap the two readline()-s into a try-except block
- catch the end-of-file exception (EOFError) and break
(break will 'stop' the while-loop)
- which will execute the two close()-s


Web.Refs:
https://docs.python.org/3/tutorial/introduction.html?highlight=concatenation
https://docs.python.org/3/reference/compound_stmts.html
https://docs.python.org/3/library/exceptions.html


* If you prefer the context manager (which I probably would) and 
understand their use-and-abuse, then it is possible to open multiple 
files using a 'nested with' construct.

An example: 
https://deeplearning.lipingyang.org/2017/01/15/open-multiple-files-using-open-and-with-open-in-python/

but please note that the try-except as-illustrated, is designed to catch 
errors at the file-level, eg file does not exist, or file cannot be 
opened; ie the "run-time exception" mentioned above; and is quite a 
separate consideration from the try-except block proposed in "answer" 
(above)!
-- 
Regards =dn


More information about the Tutor mailing list