• Register

In order to know how to count the number of lines in a text file in Python, you have to know open() function in Python. In this tutorial, we will learn to count the number of lines in text files using Python.

Text files can be used in many situations. For example, you may save your data with Python in a text file or you may fetch the data of a text file in Python. In my previous, I have shown you How to create a text file in python.

Now I will show you how to count the number of lines in a text file.

getting number of references from txt file

# read all lines of file and return an array
def read_lines(file_name):
  with open(file_name) as f:
    lines = f.readlines()
  
  return lines
  
# count number of items in a string split by some character
def count_num_split_items_in_str(string, character):
  split_result = string.split(character)
  length_of_split_result = len(split_result)
  return length_of_split_result

# create a map (dictionary) where the key is the refId and the value is the count
def count_refs(lines):
  ref_map = {} # https://docs.python.org/2/tutorial/datastructures.html#dictionaries
  
  for line in lines:
    split_line = line.split("\t")
    refId = split_line[0]
    matches_string = split_line[1]
    ref_map[refId] = count_num_split_items_in_str(matches_string, ",")
  
  return ref_map
  
def print_results_to_file(final_count_map, file_name):
  print('Writing results to file {}'.format(file_name))
  header = '\t'.join(['refid', 'count'])
  lines = [header]
  for key, value in final_count_map.items():
      line = '\t'.join(map(str, [key, value]))
      lines.append(line)

  o = open(file_name, 'w')
  o.writelines('\n'.join(lines))
  o.close()

  print('Write complete :)')
  
# constants
INPUT_FILE_NAME = 'otu_map_2.txt'
OUTPUT_FILE_NAME = 'ref_counts.txt'

# THIS IS WHERE THE MAGIC HAPPENS
all_lines_in_file = read_lines(INPUT_FILE_NAME)
ref_count_map = count_refs(all_lines_in_file)
print_results_to_file(ref_count_map, OUTPUT_FILE_NAME)

 

1,760 points
6 1