Programming Languages war Python, PHP, Javascrip (Nodejs) Read txt file

Carlos Rivas's photo
Carlos Rivas

Published on Dec 28, 2020

3 min read

Hey my friends, a new post about this war. I don't know which is better, but I'll try to figure it out. I hope y'all enjoy this series. Here we go!

It's regular in the job environment to have to read txt files, for logs o for getting any information.

For this example, you need to create a file called "readme.txt" with 6 lines into it.

Python

You need to call the function "open". This function is about to open the document, into the function you add the path of the file that you want to open, and the method of opening in this case "read", and assign this file to a variable, In this case I use the way "with" because this avoid the file stay open, this file you can read the lines with the function "read".

with open("readme.txt", "r") as f:
  print(f.read())

PHP

You need to call the function "fopen". This function is for to open document, into the functions you add the path of the file that you want to open, and the method of opening in this case "read", and assign this file to variable, this file you can read the lines with the function "fread" you're sending like parameters the variable and other function with catch the size from file. Next, you have to close file like a good practice.

<?php

$myfile = fopen("readme.txt", "r")
echo fread($myfile,filesize("readme.txt"));
fclose($myfile);

?>

Javascript

You need to import the method "fs" this method is important to manage the files, So this method have the function "readFile". You have to send a file's path, encoding file and callback (function), with this function you can get the data in the file to print or manipulate.

var fs = require('fs');

fs.readFile('readme.txt', 'utf8', function(err, data) {
    console.log(data);
});

Conclusion

Structure: They are very similar, change a little for the braces and functions' name Lines: Python: 2, PHP: 7, Javascript: 4 Time to execution: For this test I use a file of 91.5MB, and I ran 3 times. Python: 2.520s, PHP: 1.373s, Javascript: 1,561s

Would you like that I write about more info about files' functions?

I hope you enjoy my post and remember that I am just a Dev like you!

 
Share this