Files

Acknowledgement : the contents of this notebook are partially based on the book "Starting Out with Python (3rd Edition)".

When a program needs to save data for later use, it writes the data in a file. The data can be read from the file at a later time. Examples of commercial softwares that save data to files include word processors, image editors, spreadsheets, and games.

There are always three steps that must be taken when using a file in a program.

  • Open the file
  • Process the file
  • Close the file

Opening a file

file_variable = open(filename,mode)

In [2]:
student_file = open('students.txt','r')
In [5]:
print(type(student_file))
<class '_io.TextIOWrapper'>
In [11]:
customer_file = open('customers.txt','w')
In [12]:
print(type(customer_file))
<class '_io.TextIOWrapper'>

Writing data to a file

file_variable.write(string)

**note that write() is a method associated with the file object.

In [13]:
customer_file.write('Krikamol Muandet\n')
Out[13]:
17
In [14]:
name = 'Johny Depp\n'
customer_file.write(name)
Out[14]:
11
In [15]:
# closing a file
customer_file.close()

Reading data from a file

file_content = file_variable.read()

In [27]:
def main():
    # open a file named customers.txt.
    infile = open('customers.txt','r')
    
    # read the file's content 
    file_contents = infile.read()
    
    # close the file 
    infile.close()
    
    # print the file's content
    print(file_contents)
    
# call the main function
main()
Krikamol Muandet
Johny Depp

In [16]:
# readline function
def main():
    #open a file named customers.txt.
    infile = open('customers.txt','r')
    
    # read two lines from the file 
    line1 = infile.readline()
    line2 = infile.readline()
    
    # close the file 
    infile.close()
    
    # print the file's content
    print(line1)
    print(line2)
    
# call the main function
main()
Krikamol Muandet

Johny Depp

Concatenating a newline to a string

In [18]:
def main():
    # get three names
    print('Enter the names of three friends.')
    name1 = input('Friend #1: ')
    name2 = input('Friend #2: ')
    name3 = input('Friend #3: ')
    
    # open a file named friends.txt
    myfile = open('friends.txt','w')
    
    # write the names to the file
    myfile.write(name1 + '\n')
    myfile.write(name2 + '\n')
    myfile.write(name3 + '\n')
    
    # close the file 
    myfile.close()
    print('The names were written to friends.txt.')
    
# call the main function
main()
Enter the names of three friends.
Friend #1: john
Friend #2: jack
Friend #3: joe
The names were written to friends.txt.

Reading a string and stripping a newline from it

In [19]:
# rstrip function
def main():
    #open a file named customers.txt.
    infile = open('customers.txt','r')
    
    # read two lines from the file 
    line1 = infile.readline()
    line2 = infile.readline()
    
    # close the file 
    infile.close()
    
    # strip the \n from each string
    line1 = line1.rstrip('\n')
    line2 = line2.rstrip('\n')
    
    # print the file's content
    print(line1)
    print(line2)
    
# call the main function
main()
Krikamol Muandet
Johny Depp

Appending data to an existing file

In [20]:
myfile = open('customers.txt','a')
myfile.write('John\n')
myfile.write('Chris\n')
myfile.close()

Writing and reading numeric data

In [21]:
# This program demonstrates how numbers must be converted to string 
# before they are written to a text file.
def main():
    # open a file for writing 
    outfile = open('numbers.txt','w')
    
    # get three numbers from the user.
    num1 = int(input('Enter a number : '))
    num2 = int(input('Enter another number : '))
    num3 = int(input('Enter another number : '))
    
    # write the numbers to the file.
    outfile.write(str(num1) + '\n')
    outfile.write(str(num2) + '\n')
    outfile.write(str(num3) + '\n')
    
    # close the file
    outfile.close()
    print('Data written to numbers.txt')
    
# call the main function
main()
Enter a number : 10
Enter another number : 15
Enter another number : 20
Data written to numbers.txt
In [22]:
# This program demonstrates how numbers that are read from a file
# must be converted from strings before they are used in a math operation.

def main():
    # open a file for reading
    infile = open('numbers.txt','r')
    
    # read three numbers from the file.
    num1 = int(infile.readline())
    num2 = int(infile.readline())
    num3 = int(infile.readline())
    
    # close the file
    infile.close()
    
    # add the three numbers
    total = num1 + num2 + num3
    
    # display the numbers and their total
    print('The numbers are :',num1,num2,num3)
    print('Their total is :',total)
    
# call the main function
main()
The numbers are : 10 15 20
Their total is : 45

Using Loops to Process Files

Files usually hold large amounts of data, and programs typically use a loop to process the data in a file.

In [23]:
# This program reads all of the values in the students_scma241.csv file

def main():
    # open the file for reading
    students_file = open('students_scma241.csv','r')
    
    # read the first line from the file
    line = students_file.readline()
    
    # check if we reach the end of file
    while line != '':
        
        # display the value
        print(line)
        
        # read the next line
        line = students_file.readline()
        
    # close the file
    students_file.close()
    
# call the main function
main()
5601033,Mr.,JAKRAWAL,KONGKITPAISAN

5805010,Mr.,KANROP,HOOKAEW

5805012,Ms.,KANRAWEE,WISETWONGSA

5805020,Mr.,KRIANGKRAI,WUTTHISARINGKARN

5805032,Ms.,CHARINPORN,UTHONDAN

5805037,Mr.,CHETTAPORN,CHUESUPHAN

5805045,Ms.,NUTNICHA,THISACHAMADEE

5805046,Ms.,NATNICHA,YASINTHORN

5805049,Mr.,NATTANON,ATTAKITMONGKOL

5805051,Mr.,NUTTAPON,PEUNGTHONG

5805052,Ms.,NATTHAMON,SUKPHADUNG

5805086,Mr.,PRAPAT,TRAIMURATI

5805095,Mr.,PHOTCHARAPHONG,RODMANEE

5805097,Ms.,PORNNAPA,KONACHAIYAPOOM

5805098,Ms.,PORNSAKUL,BOONSOONTI

5805102,Ms.,PATTANAN,BOONYOUKONG

5805117,Mr.,MARUT,KUNLAWONG

5805161,Ms.,SUPINYA,NOPCHUMNAN

5805168,Ms.,ONKANYA,LIMPHATTHARACHAI

5805173,Mr.,EAKSIT,BUATHONG-IEM

5805175,Ms.,KANOKWAN,SRISONGKRAN

5805194,Ms.,CHANYANUT,SIRIPHETSOMBUT

5805206,Ms.,NATTHA,PASALAPHAN

5805208,Ms.,NATTAKARN,ONRAK

5805210,Ms.,NUTCHA,ZAZUM

5805250,Ms.,PANCHARAT,SAMATI

5805254,Ms.,PUNYAPHORN,NGOWSAWAT

5805279,Ms.,YOLCHAYA,JUNGPRASERT

5805289,Ms.,SARUTAYA,CHAROENRAJ

5805304,Ms.,ONNICHA,KANGKASUWAN

5805313,Mr.,CHAWAPHAK,SANGRAT

Using for Loop to read line

for variable in file_object:
      statement
      statement
      etc.

In [24]:
# This program uses the for loop to read all of the 
# values in the text file

def main():
    # open the file for reading
    students_file = open('students_scma241.csv','r')
    
    # read all the lines from the file
    for line in students_file:
        
        # display the value
        print(line)
        
    # close the file
    students_file.close()
    
# call the main function
main()
5601033,Mr.,JAKRAWAL,KONGKITPAISAN

5805010,Mr.,KANROP,HOOKAEW

5805012,Ms.,KANRAWEE,WISETWONGSA

5805020,Mr.,KRIANGKRAI,WUTTHISARINGKARN

5805032,Ms.,CHARINPORN,UTHONDAN

5805037,Mr.,CHETTAPORN,CHUESUPHAN

5805045,Ms.,NUTNICHA,THISACHAMADEE

5805046,Ms.,NATNICHA,YASINTHORN

5805049,Mr.,NATTANON,ATTAKITMONGKOL

5805051,Mr.,NUTTAPON,PEUNGTHONG

5805052,Ms.,NATTHAMON,SUKPHADUNG

5805086,Mr.,PRAPAT,TRAIMURATI

5805095,Mr.,PHOTCHARAPHONG,RODMANEE

5805097,Ms.,PORNNAPA,KONACHAIYAPOOM

5805098,Ms.,PORNSAKUL,BOONSOONTI

5805102,Ms.,PATTANAN,BOONYOUKONG

5805117,Mr.,MARUT,KUNLAWONG

5805161,Ms.,SUPINYA,NOPCHUMNAN

5805168,Ms.,ONKANYA,LIMPHATTHARACHAI

5805173,Mr.,EAKSIT,BUATHONG-IEM

5805175,Ms.,KANOKWAN,SRISONGKRAN

5805194,Ms.,CHANYANUT,SIRIPHETSOMBUT

5805206,Ms.,NATTHA,PASALAPHAN

5805208,Ms.,NATTAKARN,ONRAK

5805210,Ms.,NUTCHA,ZAZUM

5805250,Ms.,PANCHARAT,SAMATI

5805254,Ms.,PUNYAPHORN,NGOWSAWAT

5805279,Ms.,YOLCHAYA,JUNGPRASERT

5805289,Ms.,SARUTAYA,CHAROENRAJ

5805304,Ms.,ONNICHA,KANGKASUWAN

5805313,Mr.,CHAWAPHAK,SANGRAT

Processing Records

The data that is stored in a file is frequently organized in records. A record is a complete set of data about an item, and a field is an individual piece of data within a record.

In [1]:
# This program gets student data from the user and saves it as records
# in the text file

def main():
    # get the number of student records to create
    num_students = int(input('How many student records? '))
    
    # open a file for writing
    std_file = open('students_record.txt','w')
    
    # get each student's data and write it to the file
    for count in range(1,num_students+1):
        
        # get the data for a student
        print('Enter data for student #',count,sep='')
        name = input('Name : ')
        id_num = input('ID : ')
        dept = input('Department : ')
        
        # write the data as a record to the file
        std_file.write(name + '\n')
        std_file.write(id_num + '\n')
        std_file.write(dept + '\n')
        
        # display a blank line
        print()
        
    # close the file
    std_file.close()
    print('Student records written to students_record.txt')
    
# call the main function
main()
How many student records? 2
Enter data for student #1
Name : Krikamol Muandet
ID : 123456
Department : Math

Enter data for student #2
Name : Elephant
ID : 67890
Department : Physics

Student records written to students_record.txt
In [2]:
# This program displays the records that are in the students_record.txt file.

def main():
    # open the students_record.txt file
    std_file = open('students_record.txt','r')
    
    # read the first line from the file
    name = std_file.readline()
    
    while name != '':
        # read the ID number field
        id_num = std_file.readline()
        
        # read the department field
        dept = std_file.readline()
        
        # strip the newlines from the fields
        name = name.rstrip('\n')
        id_num = id_num.rstrip('\n')
        dept = dept.rstrip('\n')
        
        # display the record
        print('Name : ',name)
        print('ID : ',id_num)
        print('Dept :',dept)
        print()
        
        # read the name field of the next record
        name = std_file.readline()
        
    # close the file
    std_file.close()
    
# call the main function
main()
Name :  Krikamol Muandet
ID :  123456
Dept : Math

Name :  Elephant
ID :  67890
Dept : Physics

In [ ]: