Python

Write an awesome doc for Python. A very nice an practical one extracted from Python official documentation.

View on GitHub

Reading and Writing Files

We get data from a user via keyboard or other means, then we process it in our app and eventually we wanna store data permanently.

Files and Directories

File path in Linux and Windows

Some Settings – Windows Only

Enable file extension setting

[!CAUTION]

Here I also have the “Hidden items” ticked. It is right below the “File name extensions”.

[!CAUTION]

In Windows filenames are case-insensitive, i.e. hello.py is the same as HeLLo.PY. But this is not the case in Linux. So as a general guide treat filenames as case-sensitive.

Terminal or Command Prompt

cmd in Windows

Command Explanation Linux Windows
To clear your screen clear cls
Change drive n/a. d:
List all files inside a directory ls dir
Print current working directory pwd cd
Change directory cd cd

[!NOTE]

Learn it in Persian if youi like to learn more:

Relative VS Absolute Path

  Relative Absolute
Linux ../modules/cut.py /home/kasir/proj/modules/cut.py
Windows ..\modules\cut.py C:\Users\kasir\proj\modules\cut.py
  You’re going there from where you are right now You’ll get there no matter where you are in right now.
  E.g. you ask where is starbucks near me. And they’ll say, take the next left, turn right at the school, and it’s straight in front of you (works only relative to where you’re now). E.g. when we wanna open a website we need to provide the full address: https://docs.python.org/3/tutorial/inputoutput.html

[!TIP]

  • . points to the current directory.
  • .. points to the directory above the current one.

What is a Text File?

open(filename, mode='r', encoding=None)

Create a file called message.txt next to your project (type whatever you like inside it). And next to it create a python file with the following content:

message_file = open('message.txt', 'r', encoding="utf-8")
for line in message_file:
    print(line)
message_file.close()

[!NOTE]

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and easier to read. Later you’ll also be introduced to f.readline()

with

with open('message.txt', encoding="utf-8") as f:
    read_data = f.read()
    # ...

[!CAUTION]

Calling f.write() without using the with keyword or calling f.close() might fail to write everything to the disk, even if the program exits successfully.

[!TIP]

After a file object is closed, either by a with statement or by calling f.close(), attempts to use the file object will automatically fail:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.

Methods of File Object

Working with JSON files

[!TIP]

The JSON format is commonly used by modern applications to allow for data exchange.

Serialization & Deserialization

Example of Working with JSON Files

  1. Create a python file and use either dumps or dump code:

    dumpsdump
    ```python import json with open("user.json", "a+", encoding="utf-8") as json_file_object: serialized_user = json.dumps( {"username": "pythonic", "favorite_books": [{"name": "Narconomics"}], "groups": [], "age": "45", "gender": None}) print(serialized_user) json_file_object.write(serialized_user) ``` ```py import json with open("user.json", "a+", encoding="utf-8") as json_file_object: json.dump( {"username": "pythonic", "favorite_books": [{"name": "Narconomics"}], "groups": [], "age": "45", "gender": None}, json_file_object) ```
  2. Open the JSON file and check what is being stored inside the gender. It is null and not None. That’s a special type in JavaScript which is kinda equivalent to None.
  3. Now you can read that same file again, delete all of your codes in that python file and instead write the following:

    import json
    with open("user.json", "r", encoding="utf-8") as json_file_object:
        deserialized_user = json.load(json_file_object)
        print(deserialized_user)
        print(type(deserialized_user))
    

    And now you can see in your terminal that it prints None for gender. This is what I mean by serialization a deserialization.

[!TIP]

JSON files must be encoded in UTF-8, thus the reason behind using encoding="utf-8" when opening/creating the user.json file.

YouTube/Aparat

Ref