-2

I need to count the number of lines in any data file I input. The file can be any .txt file with a two-digit number on each line.

How can I make this work with any data file, not just one specific one? How do I convert the file into a string and then store it in a variable? And does this mean I just have to count the number of lines in the file?

#to open the file
file = input('Please enter the file name: ')
file = open(file, 'r')

#to display name of the assignment
    for assignment in file: 
    print('Results for', assignment)
    break
  • 1
    Does this answer your question? [How to get line count of a large file cheaply in Python?](https://stackoverflow.com/questions/845058/how-to-get-line-count-of-a-large-file-cheaply-in-python) – ltd9938 Feb 24 '20 at 14:20
  • What do you mean by *Counting number of elements in a data* ? Number of unique elements? Or just number of lines as you have each number in new line? – Ch3steR Feb 24 '20 at 14:21
  • Question: what is element? Counting lines, or digits in file, or sum them up? – Michał Zaborowski Feb 24 '20 at 14:21
  • Sorry, by element I mean counting lines. –  Feb 24 '20 at 14:47

2 Answers2

1

To count lines in file do:

with open(file) as f:
    print(len(f.readlines()))

readlines will read file into a list of lines, len will get length of that list and finally print will print it out

But it is a naive solution with memory consumption O(n) where n is count of lines in file. Better do that:

i = 0
with open(file) as f:
    for line in f:
        i += 1
Pavel Shishmarev
  • 1,335
  • 9
  • 24
  • Hi, I get an error that reads: Traceback: with open(file) as f: TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper –  Feb 24 '20 at 14:31
  • Do you use Python 2? Don't use it, it's not supported now, you should consider migrating to Python 3 – Pavel Shishmarev Feb 25 '20 at 14:08
1
count = 0
with open(file) as tests:
        for curline in tests: #for each line
            count+=1 #add int of line to total
print(count)

this is untested but something like this may work? looping through each line converting it to an integer and appending a total

file must be the path to your file or the filename if its in the same directory as your python file. must be a string such as "testfile.txt" or "./files/myfile.txt"

if you are summing then change count to

count+=int(curline)
Charlie
  • 75
  • 10