[Python] Read data into array
This article is a follow-up of my previous perl script to manipulate data in a file. After I posted my question on a social website, I've received a lot of people encouraging me to do it in Python.
Some advantages of Python over Perl are: easier to maintain, easier for other people to read, and even google programmers use it. And there is claim out there saying that if you know C++, you could easily pick up Python. (Alright, I have to admit that the main reason is that googlers use it ..)
So I started learning Python and trying to write a Python script to do the same task:
- read in data from a file
- and store elements in arrays
- do simple calculations
- output result
In this Python script, it also takes input file name in the argument. First we need to import two modules:
| import os |
| import sys |
| filename = sys.argv[1] |
| lines = [line.strip() for line in open(filename).readlines()] |
| for i in lines: |
| row = i.split() |
| id.append(int(row[0])) |
| y.append(float(row[1])) |
| id = [] |
| y = [] |
Once we have the values stored in arrays, we can easily manipulate them. To output the results, we could use the open function:
| output = open("output.txt",'w') |
| for i in range(len(y)) |
| output.write("%2d\t %12f\n" %(id[i],y[i])) |
| output.close |
I might spend more time writing this Python script than I did my for perl one, but it is easier to follow. And also because the indent rules python requires, so the code looks more neat.
Hooray! My first Python code!!