Python 3

home

Introduction to Python

davidbpython.com




Data Parsing & Extraction: File Operations and the for Looping Statement


the for loop block statement with a list

for with a list repeats its block as many times as there are items in the list.


mylist = [1, 2, 'b']

for myvar in mylist:     # myvar = next(mylist)   (i.e., <B>1</B>)
    print(myvar)         # 1
    print('===')         # ===
print('done')

The above code produces this output:

# 1
# ===
# 2
# ===
# b
# ===
# done


Ex. 4.12






review: the concept of incrementing

We reassign the value of an integer to effect an incrementing.


x = 0         # int, 0

x = x + 1     # int, 1
x = x + 1     # int, 2     (can also say x += 1)
x = x + 1     # int, 3

print(x)      # 3






using a for loop to count list items

An integer, incremented once for each iteration, can be used to count iterations.


mylist = [1, 2, 'b']

my_counter = 0

for thisvar in mylist:
    my_counter = my_counter + 1

print(f'count:  {my_counter} items')   # count:  3 items






using a for loop to sum list items

A float value, updated for each iteration, can be used to sum up the values that it encounters with each iteration.


mylist = [1, 2, 3]

my_sum = 0

for val in mylist:
    my_sum = my_sum + val

print(f'sum:  {my_sum}')     # sum: 6  (value of 1 + 2 + 3)


4.12 - 4.13






the open() function and the 'file' object

The 'file' object represents a connection to a file that is saved on disk.


fh = open('students.txt')     # a 'file' object

print(type(fh))               # <class '_io.TextIOWrapper'>






reading a file with the for statement

for with a 'file' object repeats its block as many times as there are lines in the file.


fh = open('students.txt')              # file object allows looping
                                       # through a series of strings

for xx in fh:                          # xx is a string, a line from the file;
    print(xx)                          # this prints each line of students.txt

fh.close()                             # close the file


Ex. 4.14






summarizing: csv parsing with for looping and string parsing

Here we put together all features learned in this session.


fh = open('revenue.csv')          # 'file' object

counter = 0
summer = 0.0

for line in fh:                   # str, "Haddad's,PA,239.50\n"  (first line from file)

    line = line.rstrip()          # str, "Haddad's,PA,239.50"
    fieldlist = line.split(',')   # list, ["Haddad's", 'PA', '239.50']

    rev_val = fieldlist[2]        # str, '239.50'
    f_rev = float(rev_val)        # float, 239.5

    counter = counter + 1         # incrementing once for each iteration
    summer = summer + f_rev       # adding the value found at each iteration to a sum

fh.close()

print(f'counter:  {counter}')     # 7 (number of lines in file)
print(f'summer:   {summer}')      # 662.01000001  (sum of all 3rd col values in file)


Ex 4.28






sidebar: writing and appending to files using the file object

Files can be opened for writing or appending; we use the 'file' object and the file .write() method.


fh = open('new_file.txt', 'w')
fh.write("here's a line of text\n")
fh.write('I add the newlines explicitly if I want to write to the file\n')
fh.close()

Note that we are explicitly adding newlines to the end of each line -- the write() method doesn't do this for us.





[pr]