Higher – Python – Reading from a file

Python-logo-notext.svgA lot of people find reading from a sequential file difficult. Well lets break it down, first of all what is a sequential file? A sequential file is a text based (ASCII or UNICODE) file that is made up of both printing and non printing characters. The end of the file is signalled with EoF, often programmers put data in separate lines using a new line character. Sometimes the files are in CSV format, which means that each line holds a records worth of data.

The basic premise of any Python read file access is

  1. Open file for reading
  2. read each line
  3. close file

This post will mostly be focused on different ways of doing step 2.

Getting a single piece of data from a file.

# Get single piece of data from a file and store in variable

text_file = open('single_name.txt','r') # 1. open file
name = text_file.read()                 # 2. read data from file
text_file.close()                       # 3. close file

print('The data in the file "single_name.txt" is',name)

Get multiple lines of data from a file.

# Get multiple lines of data from a file and store in an array
# Unknown number of lines

names=[]
text_file = open('classList.txt','r')   # 1. open file
for line in text_file:                  # 2. read data from file
    names.append(line[:-1])             #    The [:-1] removes the new line char
text_file.close()                       # 3. close file

print('The data in the file "classList.txt" is',names)

Reading from a CSV into records

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Get data from a CSV file, unknown number of lines
# Read into record

names=[]

csv_file = open('highscores.csv','r')   # 1. Open file
for line in csv_file:                   # 2. read data from file
    names.append(line[:-1].split(','))  # split into two variables after removing newline         
csv_file.close()                        # 3. close file

print('High Scores')
print(names)

Read data from CSV file into arrays

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Get data from a CSV file, unknown number of lines
# Read into seperate arrays

names=[]
scores=[]
csv_file = open('highscores.csv','r')   # 1. Open file
for line in csv_file:                   # 2. read data from file
    name,score=line[:-1].split(',')     # split into two variables after removing newline
    names.append(name)
    scores.append(int(score))           # change score to Integer
csv_file.close()                        # 3. close file

print('High Scores')
print(names)
print(scores)

There are other constructs we can use to read data from files but the steps remain the same.

  1. Open file for reading
  2. read each line
  3. close file

I have attached the files I used

Leave a Reply

Your email address will not be published. Required fields are marked *