user3636636
user3636636

Reputation: 2499

Function that opens a file for reading and returns the number of bytes and newlines

I currently working my way through a free online python school. The following template has been given to me, and I am to complete the function so that it returns the size of the file (number of bytes) and the number of newlines ("\n"). I'm completely stuck. Any help would be appreciated.

def readFile(filename):
    f = open(filename)
    size = 0
    lines = 0
    buf = f.read()     
    while buf!="":



        buf = f.read() 

    f.close()                 

    return (size, lines)

Upvotes: 1

Views: 376

Answers (2)

cchristelis
cchristelis

Reputation: 2015

So the buf variable contains a chunk of data.

Since you are still learning I will use a very basic approach:

nl_count = 0  # Number of new line characters
tot_count = 0  # Total number of characters
for character in buf:
    if character == '\n':
         nl_count += 1
    tot_count += 1

Now you will have to adjust this to fit to your code, but this should give you something to start with.

Upvotes: 2

jonnybazookatone
jonnybazookatone

Reputation: 2268

You could read all the lines in at once and use the list rather than the file itself. For example,

def readFile(filename="test.txt"):

  f = open(filename)

  # Read all lines in at once
  buf = f.readlines()
  f.close()

  # Each element of the list will be a new line
  lines = len(buf)

  # The total of the total of each line
  size = sum([len(i) for i in buf])

  return (size, lines)

Upvotes: 0

Related Questions