home ~ projects ~ socials

Read The First Line Of A File In Python

def read_first_line(path):
  with open(path) as _in:
    return(_in.readline().strip())

first_line = read_first_line("read_first_line.txt")
print(first_line)
Output:
Alfa bravo charlie

Notes

  • Reads the first line of a file and returns it
  • Any leading and trailing whitespace is removed from the line (including the trailing newline if it exists)
-- end of line --