Python3.4 – Advanced Reading from Files

About 15 weeks ago, I was making my first steps in Python (sometimes it is a pity that I do not have dates on my articles, but I like it this way). 

Python

During my first steps, once I had the following tasks:

  • Implement the cat command – Print file contents;
  • Cat multiple files;
  • Generate file with random integers;
  • Sum integers from file;
  • Get the file size of a file.

Detail descriptions of the tasks could be found here.

So, why do I bother you with all these? Because the task is interesting in the part, that you pass the arguments from the console. This part worths the whole article. The rest is trivial. 🙂

So let’s start with the first and the second task together. Implement a program, that prints on the console the content of any file which you pass as an argument. The result looks like this:

print2files

So, how is it achieved? With the following code we read all the arguments after the name of the file:

In our case “w2b.py” is the name of the file and “read2.txt” and “read.txt” are the files, which we read. Thus, the whole code looks like this:


Concerning the next task, the generation of random numbers in file, I have decided to add one variable, which is read from the console, telling us how much numbers to generate. The code is simple, when it is divided into two functions, each doing its work:


Next, we need to sum the integers from the file which we have generated. In this case, we simply read the file and split its content into a list. The sum of a list is a built-in function in Python:


The last calculation to do is concerning the file size. Python gives us a built-in function for this: os.path.getsize(sys.argv[1]). Thus, in our case it is just two lines (which can be made into one actually):


Pretty much that is all. The whole code is available in my GitHub repo.
Enjoy it 🙂

Tagged with: , ,