Friday, February 10, 2017

Python Advanced #11 - Reading Two Columns from a Non-Justified Text File and Saving to a Justified Text File

In Python Advanced #10, we read two columns from a non-justified text file and saved those values into lists.  Recall that the non-justified text file was as follows:

Using the code developed in Python Advanced #10 and adding code to write the results of the lists named vals1 and vals2 to a text file, the code is as follows:

However, when we look at the resulting text file, we can see that the values are not justified.

To solve this issue, I use rjust in the write statement to right justify the values.  Note that the number in the parentheses specifies the desired width of the column.  The new write statement now looks like this:

The output from changing this write statement is shown below:

Wednesday, February 1, 2017

Python Advanced #10 - Reading Two Columns from a Non-Justified Text File and Saving into Lists

In this post, we start with a non-justified text file as shown below.  This file is titled nonjust.txt.

Our objective is to extract the first and last columns and then save those into lists.  I will be exporting them to a different text file in a future post.  We do this by using the code below.

We first open the text file that contains the text.  We create empty lists to store the first column (vals1) and to store the last column (vals2).  An additional empty list (templist) is used to store the values found on each line.  In the while loop, we first use the split command on the current line to create three separate value to populate templist.  Without using the split command, we would have a single string.  We then append the first value (position 0 in templist) to vals1 and append the third value (position 2 in templist) to vals2.  We then clear templist of its contents and read the next line in the text file.  After the while loop concludes, we then print vals1 and vals2 to check the contents of the list.

The results from this program are shown below.