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).
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:
So, how is it achieved? With the following code we read all the arguments after the name of the file:
1 |
for arg in sys.argv[1:]: |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
import sys import os from random import randint def main(): for arg in sys.argv[1:]: filename = arg file = open(filename, "r") content = file.read() print(content) file.close |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def GenerateRandoms(n): sRandoms = "" i = 0 while i < n: sRandoms += str(randint(1, 1000)) + " " i += 1 sRandoms.strip return sRandoms def randomNumbers(): filename = sys.argv[1] file = open(filename, "w") contents = GenerateRandoms(int(sys.argv[2])) file.write(contents) file.close |
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:
1 2 3 4 5 6 7 8 9 10 11 |
def calculate(): filename = sys.argv[1] file = open(filename, "r") content = file.read() file.close myList = list() myList = content.split() myList = [int(i) for i in myList] print(sum(myList)) |
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):
1 2 3 4 5 6 7 |
def fileSize(): try: total_size = os.path.getsize(sys.argv[1]) print(total_size, " bits", sys.argv[1]) except OSError: print("Error -> File name not correct") |
Pretty much that is all. The whole code is available in my GitHub repo.
Enjoy it 🙂