You may want to open two or more files at the same time in Python. For example, you might want to read one file, do some processing, and write the result to another file.
If you write a program obediently,
with open('./output.txt', mode='w') as fw:
with open('./input.txt', mode='r') as fi:
for line in fi:
i = int(line.strip())
i += 1 #Processing just by adding 1
fw.write(str(i) + '\n')
I think it will be.
ʻInput.txt`
1
2
3
If so, ʻoutput.txt` is
2
3
4
It will be.
However, the above program is not smart because the with
clause is nested and the indentation is deep.
Actually, in this program, you can write the with
clauses together as follows.
with open('./input.txt', mode='r') as fi, open('./output.txt', mode='w') as fw:
for line in fi:
i = int(line.strip())
i += 1 #Processing just by adding 1
fw.write(str(i) + '\n')
I think the indentation has become shallower and a little (?) Smarter.
Recommended Posts