Open main menu

CDOT Wiki β

OPS435 Python Exercise 1

Objectives

  • read a single line from a text file
  • split a single line into words and store all the words in a list
  • combine selected items from a list to make useful data object
  • manipulate data objects: date, time, user name, host IP

Read a single line from a text file

  • file name: test_data_0
  • contents:
[rchan@centos7 ex1]$ cat test_data_0 
rchan    pts/9        10.40.91.236     Tue Feb 13 16:53:42 2018 - Tue Feb 13 16:57:02 2018  (00:03)    
asmith   pts/2        10.43.115.162    Tue Feb 13 16:19:29 2018 - Tue Feb 13 16:22:00 2018  (00:02)    
tsliu2   pts/4        10.40.105.130    Tue Feb 13 16:17:21 2018 - Tue Feb 13 16:30:10 2018  (00:12)    
mshana   pts/13       10.40.91.247     Tue Feb 13 16:07:52 2018 - Tue Feb 13 16:45:52 2018  (00:38)

Python Code to read a single line (first line) from a file:


  file_name = 'test_data_0'
  f = open(file_name,'r')
  line_in = f.readline()
  print(line_in)

Output of the above python code:

rchan    pts/9        10.40.91.236     Tue Feb 13 16:53:42 2018 - Tue Feb 13 16:57:02 2018  (00:03)

Split a single line into words and store all the words in a list

Python code to split the line "line_in" into words:

  word_list = line_in.split() # <-- split the line into words using space
                              # store all the words as a list to word_list
  print(word_list) # <-- you should see the list of word when this line is executed

Output from the above print() function:

['rchan', 'pts/9', '10.40.91.236', 'Tue', 'Feb', '13', '16:53:42', '2018', '-', 'Tue', 'Feb', '13', '16:57:02', '2018', '(00:03)']

selected items from a list to make useful data object

login date and logout date

Login date in YYYYmmmdd format:

   login_date = word_list[7]+word_list[4]+word_list[5]
   print('Login date:',login_date)

The output will be:

Login date: 2018Feb13

Logout date in YYYYmmdd format:

   logout_date = word_list[13]+word_list[10]+word_list[11]
   print('Logout date:, logout_date)

The output will be:

Logout date: 2018Feb13

login time and logout time

   login_time = word_list[6]
   print('Login time:',login_time)

The output will be:

Login time:

manipulate data objects: date, time, user name, host IP