Home > Blockchain >  Count of lines in a file in python3
Count of lines in a file in python3

Time:04-12

How to print a number of lines edited by an arithmetic operation to a file, please? Let's say that multiplied by 2, for simplification. I tried:

f = open(f'file.dat', 'rw')
it = sum(1 for _ in f)*2
f.write("A  B  C line: \n")
f.write("\n")
f.close()

Desired result:
A  B  C line: 2
A  B  C line: 4
A  B  C line: 6

I obtain an error:

io.UnsupportedOperation: not readable

CodePudding user response:

You could do the following:

  1. Open the file in r mode.
  2. read the previous lines and sum the values
  3. write a new line to the file.
with open("bleh.txt", 'r ') as fp:
    it = sum(1 for _ in fp) * 2
    fp.write("A  B  C  line: %d\n" % it)

The problem with this approach is that if the file doesn't exist, it chokes.

So, change r to a .

So the final code:

with open("bleh.txt", "a ") as fp:
    it = sum(1 for _ in fp) * 2
    fp.write("A  B  C  line: %d\n" % it)

Of course... with a mode, the file pointer is placed at the end of the file. So.. the following needs to be added:

with open("bleh.txt", "a ") as fp:
    fp.seek(0)
    it = sum(1 for _ in fp) * 2
    fp.write("A  B  C  line: %d\n" % it)

This moves the file pointer back to the beginning.

  • Related