Difference between revisions of "OPS435 Python Exercise 1"
(→Read a single line from a text file) |
(→Read a single line from a text file) |
||
Line 27: | Line 27: | ||
Output of the above python code: | Output of the above python code: | ||
<pre> | <pre> | ||
− | + | rchan pts/9 10.40.91.236 Tue Feb 13 16:53:42 2018 - Tue Feb 13 16:57:02 2018 (00:03) | |
</pre> | </pre> | ||
Revision as of 21:09, 21 June 2018
Contents
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