简体   繁体   中英

How can I correct count lines in text file in Python and get its size in bytes?

I have trouble to get correct values for an exercise with the following instructions. Write a function that open a file for reading and returns the number of bytes and newlines('\\n').

I should get values for def readFile(tmp.txt) is (12, 4) , but I got (11, 5) .

Where I am doing wrong and could you explain me in great details why is that.

def readFile(filename):
    f = open(filename, 'r')
    size = 0 # Total size in bytes of all lines in a text file
    lines = 0 # Total number of lines
    buf = f.readline() # Read a line    
    while buf != "":
        buf = f.readline() # Read a line
        size += len(buf)
        lines += 1  # Count lines
    f.close  # Close a file              

    return (size, lines) 

os.path.getsize(filename) will return the number of bytes, see here . With file.read() the entire contents of the .txt file can be read and returned, see here . You can then use the method .count("\\n") to count the number of occurrences of \\n. I recommend reading the paragraphs on .close() and using the with keyword as well (see previous link).

Note: The following code snippets assume that tmp.txt is in the same folder as the .py file.

import os


def read_file(filename):
    nr_of_bytes = os.path.getsize(filename)
    with open(filename, "r") as file:
        nr_of_newlines = file.read().count("\n")
    return nr_of_bytes, nr_of_newlines

print(read_file("tmp.txt"))

Shorter version:

import os


def read_file(filename):
    with open(filename, "r") as file:
        nr_of_newlines = file.read().count("\n")
    return os.path.getsize(filename), nr_of_newlines

print(read_file("tmp.txt"))

Finaly I managed to get correct result. Here is a code, perhaps with unusual approach since some inbuilt functions mentioned above does not work while coding in Pyschool website.

    def readFile(filename):
    f = open(filename, 'r')
    string1 = f.read()  # Read file
    size = len(string1) # Getting file size, assuming length of a string represent 
                        # file size (python 2.x)
    f.close             # We close file temporarily, once we read all bytes,
                        # we cannot read file again (based on my experience with Python, perhaps I am wrong)

    d = open(filename, 'r')      # Again we open same file
    lines = d.read().count("\n") # Counting '\n'
    d.close                      # We close file

    return (size, lines)         # Return result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM