banner

© 2004-19 ict4u.net

Reading a Text

Text files are very easy to process with Python
  1. open the file and assign a file handler
  2. two methods of reading the file one with a newline character, the other without
  3. process the data in the list using standard python list methods
Download the a sample text filehere
#
# Read a text file

# # open the file assign a file handler (the name at the RHS of the equal sign)
txtFile = open('TourHighlights.txt')

# use the read method to store the contents of the file in a list variable
# AND remove the newline character from the end of the string
textFromFile = txtFile.read().splitlines()

# this is an alternative way to read the data which keeps
# the newline at the end of the input string:

# textFromFile = txtFile.readlines()

# good housekeeping - close the file once the data has been read
txtFile.close()

# fileContent can now be processed as a list datatype in the normal way
for item in textFromFile:
     # display the contents of the list
     # notice that there is an extra blank
     print (item)

# Now check to see how big the list is
numberOfLines = len(textFromFile)
print(f"\nNumber of lines: {numberOfLines} ")
#
# Print a specific line from the list (array)
print (f"\n{'!'*4}Remember lists indexes start at element 0 {'!'*4}")
print(f"line No 3: { textFromFile[3]}")