Python open()

Python open()

We will learn about the Python open() function, that is, we will see how to open a text or binary file.

In the previous lesson we talked about files and saw the difference between binary and text (or ASCII) files. In our examples we will mainly use text files for fixed and variable length archives.

Therefore, to operate on a Python language file we must perform these simple steps:

  • First open the file specifying: name, extension (mandatory) and type of access (if in writing, reading, in append mode to add content to an existing file, in reading and writing. Optional data as it has a default value which is in reading). In addition to these values there are other arguments that can be indicated and that we will see gradually in the tutorial;
  • then do the operations on the file;
  • finally close the file.
  • If the file is not in the same folder as the Python file, the correct path must be specified. If you are a beginner I recommend that you leave the file in the same folder as the Python file.

Python open()

Streams are described through classes, which are a list of properties and methods that are linked together. Once you have declared an object type variable you have all the properties and methods attached to it.

Streams are described through classes, which are a list of properties and methods that are linked together. After declaring a variable of type object, all properties and methods are associated.

One of the functions I want to introduce to you is simply Python open () function, which allows us to open a file.

Let’s see it in detail, assuming we want to open a file called coding.txt which is in the same folder as our Python file.

f = open(‘coding.txt’, ‘r’) # Open in input

Opens the file for character reading only. But be careful, if the file doesn’t exist it will give us an error!

However, we point out that the complete syntax would be this:

f = open(‘coding.txt’, mode = ‘r’)

But we can also omit mode parameter.

Note that we have declared a variable f of type object on which we will then apply the various methods.

Now let’s take another simple example:

f = open(‘coding.txt’, ‘w’) # Open in output

You open the file and allow writing to it. But be careful, if the file exists it is deleted and recreated!

Let’s see in detail the various ways of opening a file.

How to open a file in Python

Let’s deepen the open method in Python by studying in detail the various access modes.

Below is an explanatory table of the types of access to a file in Python.

ModeExampleUsage
ropen(‘coding.txt’,’r’)Default value. Create the file and open it as read-only. If the file exists it does not exist an error message is returned.
wopen(‘coding.txt’,’w’)Create the file and open it for write only. If the file exists it is deleted.
aopen (‘coding.txt’, ‘a’)Open the file in append mode, that is, it allows you to add text to an already existing file. If the file does not exist, create it.
+open(‘coding.txt’,’r+’)Open the file in read mode and write mode in append mode. Returns an error if the file does not exist.
xopen(‘coding.txt’,’x’)Create the file, returns an error if the file already exists.
topen(‘coding.txt’,’t’)Open a file in text mode.
bopen(‘coding.jpg’,’b’)Open a file in binary mode. For example for images.

Let’s now take an example by combining more options than those listed in the table above:

f = open(‘coding.jpg’, ‘r + b’)

This very simple line of code allows you to open a binary file named coding.jpg for reading and writing.

In this lesson we have therefore introduced the Python open() function in the next we will talk about the write() method.

Some useful links

Python tutorial

Python Compiler

Introduction to dictionaries in Python
Use Python dictionaries
Create dictionaries in Python
Python get() method
keys() method
items() method
pop() method
popitem() method
Sort dictionary in Python

Operations with files in Python

Operations with files in Python

In this lesson we will study how to perform operations with files in Python.

In fact, in Python, as in other programming languages, you have functions for Input / Output operations on files, not unlike those for I / O on consoles.

We remind you that with the term file we mean everything that can be recorded on a mass storage medium (hard disk, pen drive, etc.).

The file is identified by a name and extension. The name is usually significant, in order to make us understand the content that the file contains. While the extension identifies the program with which it must be run.

The operations that are performed on the files are those of:

  • open – the file, saved in the mass memory, is loaded into the main memory usually for reading or writing operations.
  • close– the file loaded in the main memory is closed, that is, the connection between the main memory and the mass memory that contains that file is interrupted.
  • read – after the opening operation, the reading can be carried out. I.e. the contents of the file are interpreted by loading it into the main memory.
  • write – after the opening operation you can perform the write operations on the file, or you can save the changes in the main memory.

Reading is indicated with INPUT (from the mass memory to the central memory). While the writing is indicated with OUTPUT (from the central memory to the mass memory). Operations that are used to transfer information from main memory to mass storage are called Input / Output operations.

Operations with files in Python – file types

Files handled by the file system can be split into text files or binary files.

But what’s the difference and why do we need to know it?

These files encode the data differently:

  • Text files, also known as ASCII files, contain end-of-line (EOL) characters and each byte represents one character of the ASCII encoding. They are suitable for storing data of different lengths, they are heavier but can be read on computers that have different operating systems.
  • Binary files, on the other hand, are considered as a continuous stream of bits, are faster in reading and writing operations, and take up less disk space.

In Python we use text files to manage textual information while binary files to manage, for example, images or sounds. We keep this information in mind for the file operations in Python that we will see in the next lessons.

In this lesson we talked about file operations in Python, in the next lesson we will study many methods to operate on files.

Some useful links

Python tutorial

Python Compiler

Introduction to dictionaries in Python
Use Python dictionaries
Create dictionaries in Python
Python get() method
keys() method
items() method
pop() method
popitem() method
Sort dictionary in Python

JavaScript to do list

JavaScript to do list

In this lesson we will create a simple JavaScript to do list, a classic JavaScript exercise that allows you to experiment with the methods learned so far.

To carry out this project, in fact, we will use some methods to manipulate the DOM in JavaScript.

In the meantime, try the project that we are going to create together by inserting an item and then clicking on the add button in the figure below:

App To Do List

To do list in JavaScript – development

First we create the HTML code of the project.

So let’s create an input box with a button and prepare a list where all the elements that we will add gradually will appear.





We then create any CSS to give a graphic touch, for example I have created this:



.container{
    background: #ff6676;
    padding: 30px;   
    display: flex;
    flex-direction: column;
}

.container h3{
    color: white;
    text-align: center;
    margin-bottom: 15px;
    height: auto;
}

form{
    display: flex;
    width: 100%;
}

.textInput{
    width: 100%;
    border: none;
    padding: 14px;
}

#add{
    width: 30%;
    cursor: pointer;
    background: #2c45a3;
    border: none;
    color: white;
    font-size: 18px;
}

ul#lists{
    display: flex;
    flex-direction: column;
    margin: 10px 0;
    list-style: none;
}

ul#lists li{
    padding: 12px;
    background: white;
    border: 1px solid #2c45a3;
    display:flex;
    justify-content: space-between;
}

.delete{
    padding: 10px;
    cursor: pointer;
    border: none;
    background: #ff6676;
    color: white;
}

Finally we develop the JavaScript code necessary to make our to do list work:



const buttonAdd = document.getElementById('add');
const lists = document.getElementById('lists');
const textInput = document.querySelector('.textInput');

buttonAdd.addEventListener('click', generateList);

function generateList(event) {
    event.preventDefault();

    if (textInput.value === '') return;

    const li =  document.createElement('li');
    lists.appendChild(li);    
    li.appendChild(document.createTextNode(textInput.value));
    
    const buttonDelete = document.createElement('button');
    buttonDelete.className = 'delete';
    buttonDelete.appendChild(document.createTextNode('X'));    
    li.appendChild(buttonDelete);
    
    textInput.value = '';
    
    buttonDelete.addEventListener('click', (event) =>{
        const parentNodeEl = event.target.parentNode;
        setTimeout(() =>{
            parentNodeEl.remove();
        }, 500)
        
    });
         
}



First of all we checked that the input box contained some text and otherwise we exit the function with a return. In this way, if the box is empty, a list is not created.

After, we used the addEventListener method to capture the first click on the add button to add an item in the list and then on the delete button to delete the corresponding item.

Within the generateList function we used the createElement and createTextNode methods respectively to create the necessary tags (li and button) and add text.

After adding the entry we empty the input box.

Conclusion

In this lesson we have developed a simple to do list in JavaScript, try developing one yourself and write in the comments below. In the next lessons we will develop many other creative projects.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript eval

JavaScript eval

The eval function in JavaScript evaluates the expression passed as an argument and executes it if there is an operation.

The syntax is as follows: eval(string).

JavaScript eval examples

Here is a series of demonstrative examples on the use of eval.



console.log(eval('2 + 13'));
var x = 10;
var y = 3;
console.log(eval('x + y'));
console.log(eval(' x / y'));

However, remember that this function is slower than the alternatives.

It can also be dangerous as it runs the code with page administrator privileges.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript functions and return

JavaScript Callback

Callbacks

Array method and callback function

Callback functions – examples

JavaScript string

JavaScript string

In this lesson we will study the JavaScript String function that is used to return a string from a value passed as an argument.

The syntax is as follows: string(object). Where object can be a number value, a Boolean value.

JavaScript string examples

These are some examples:



console.log(String('13years'));
console.log(String('thirteen'));
console.log(String('13:50'));
console.log(String('13-01-20'));
console.log(String('13 01 20'));
console.log(String('true'));
console.log(String('13.50'));
console.log(String('13'));
console.log(String(''));
var num = 10;
console.log(String(num));
var arrayNumeri = [7,12];
console.log(String(arrayNumeri));

Try these simple examples on JavaScript string method, you will always see a string in the browser console, even when we pass a numeric value.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants

Conditional instruction if, else