09 Terminal, Packages, File I/O

image.png լուսանկարի հղումը, Հեղինակ՝ Karine Avetisyan

Open In Colab (ToDo)

📚 Նյութը

Terminal

# !dir
 Volume in drive C is Windows-SSD
 Volume Serial Number is C20F-A88B

 Directory of c:\Users\hayk_\OneDrive\Desktop\python_math_ml_course\python

28-May-25  05:46 PM    <DIR>          .
25-May-25  12:13 PM    <DIR>          ..
12-May-25  05:08 PM            42,691 01_intro.ipynb
24-May-25  03:04 AM            53,188 02_conditions.ipynb
25-May-25  05:49 PM           229,401 03_str_range_list_some_funcs.ipynb
12-May-25  03:47 PM            81,015 04_loops.ipynb
12-May-25  03:09 PM           756,828 05_lst_str_methods_one_line_if_for.ipynb
22-May-25  08:27 AM            61,242 06_tuple_set_dictionary.ipynb
23-May-25  06:04 PM            81,266 07_functions_1.ipynb
24-May-25  02:01 AM           135,805 08_functions_2.ipynb
28-May-25  05:59 PM           251,156 09_files_Packages_Terminal.ipynb
24-May-25  03:09 AM               944 10.ipynb
24-May-25  02:11 AM                27 data.pkl
07-Mar-24  04:47 PM       333,379,169 elections.csv
28-May-25  05:46 PM               167 helper.py
28-Apr-25  08:13 PM            55,071 INITIAL Python _ ?9 _ Exception (Error) handling.ipynb
28-May-25  05:46 PM             1,163 main.py
24-May-25  01:13 AM    <DIR>          mini_projects
22-May-25  08:12 AM    <DIR>          wallpapers
              15 File(s)    335,129,133 bytes
               4 Dir(s)  43,172,896,768 bytes free

Terminal Commands

Below are some commonly used terminal commands with their Linux equivalents:

Windows Command Linux Command Description
dir ls Lists the files and directories in the current directory.
cd cd Changes the current working directory.
cd .. cd .. Goes up one directory level.
md / mkdir mkdir Creates a new directory.
del rm Deletes a file.
copy cp Copies a file.
move mv Moves a file or directory.
ren mv Renames a file or directory.
type cat Displays the contents of a file.
cls clear Clears the terminal screen.
tasklist ps Lists the running processes.
history history Displays the command history. *(worked only in PowerShell)
help man Displays help information for a command.
tree tree Displays the directory structure in a tree format.
echo echo Prints text or variables to the terminal.
exit exit Exits the terminal or command prompt.
find grep Searches for a specific text string in files.
attrib chmod / chown Displays or changes file attributes.

Note: Use help <command> in Windows or man <command> in Linux to get detailed information about any specific command.

(table may contain mistakes)

Files

See files py_files/files_main.py and py_files/files_helper.py

Modules (packages)

os module (դոկումենտացիա)

https://docs.python.org/3/library/index.html

import os # operating sytem
dir(os)[-10:]
['umask',
 'uname_result',
 'unlink',
 'unsetenv',
 'urandom',
 'utime',
 'waitpid',
 'waitstatus_to_exitcode',
 'walk',
 'write']
os.getcwd() # current working directory
'c:\\Users\\hayk_\\OneDrive\\Desktop\\python_math_ml_course'
os.chdir("python") # change directory
# absolute - /Users/hayk_/OneDrive/Desktop/python_math_ml_course/python
# relative - ../python

# chdir("..") # վերադառնում է վերևի ֆոլդերը
os.getcwd() # current working directory
'c:\\Users\\hayk_\\OneDrive\\Desktop\\python_math_ml_course\\python'
os.listdir("wallpapers")
['01_Dilijan.png',
 '02_Khustup.jpg',
 '03_kamaz.jpg',
 '04_fruits.jpg',
 '05_sheep.jpg',
 '06_field.jpg',
 '07_window.jpg',
 '08_rainbow.jpg']
os.listdir()
['01_intro.ipynb',
 '02_conditions.ipynb',
 '03_str_range_list_some_funcs.ipynb',
 '04_loops.ipynb',
 '05_lst_str_methods_one_line_if_for.ipynb',
 '06_tuple_set_dictionary.ipynb',
 '07_functions_1.ipynb',
 '08_functions_2.ipynb',
 '09_files_Packages_Terminal.ipynb',
 '10.ipynb',
 'data.pkl',
 'elections.csv',
 'helper.py',
 'INITIAL Python _ Տ9 _ Exception (Error) handling.ipynb',
 'main.py',
 'mini_projects',
 'wallpapers',
 '__pycache__']
'c:\Users\hayk_\OneDrive\\Desktop\\python_math_ml_course'
'c:/Users/hayk_/OneDrive/Desktop\\python_math_ml_course'

image.png

image.png
path = os.path.join('python', 'wallpapers')
print(path)
python\wallpapers

time մոդուլ (դոկումենտացիա)

import time
current_time = time.time()
print(current_time)
1748452354.123272
current_time = time.time() # / time.perf_counter()
print(current_time)

for i in range(1_000_000):
    a = i**2

end_time = time.time()
print(end_time)

print(end_time - current_time)
# 1970 թվականի հունվարի 1-ից հետո քանի վարկյանա անցել
1748452422.6269596
1748452423.3290446
0.702085018157959
1748452423.3290446
0.702085018157959

time.time() = wall-clock seconds since 1970; can jump if the system clock changes → use for timestamps. \ time.perf_counter() = monotonic, high-resolution timer that never goes backward → use for measuring code runtimes.

t = time.localtime()
print(t)
time.struct_time(tm_year=2025, tm_mon=5, tm_mday=28, tm_hour=19, tm_min=15, tm_sec=1, tm_wday=2, tm_yday=148, tm_isdst=1)
t.tm_year
2025
time_harmar = time.strftime('%Y-%m-%d %H:%M:%S', t)
# f"{year}-{month}"
print(time_harmar)
2025-05-28 19:15:01
print(1)
time.sleep(5)
print(2)
1
2
2

Write a program that will test how good is someone at timing 10 seconds

st = time.time()
_ = input("Press when you think 5 seconds have passed")
end = time.time()
print("Mistaken by: ", abs((end - st) - 5))
Mistaken by:  2.696681261062622

random (դոկումենտացիա)

import random
# random.seed(50)
# generate a random float between 0 and 1
rand_float = random.random()

# generate a random integer between 1 and 10
rand_int = random.randint(1, 10) # both inclusive

# generate a random float between 1 and 10
rand_float2 = random.uniform(1, 10)

print(rand_float, rand_int, rand_float2)
0.11948992325676466 5 8.553091071888783
my_list = [1, 2, 3, 4, 5]

rand_choice = random.choice(my_list)

print(rand_choice)
3
import random
random.seed(509)
my_list = [1, 2, 3, 4, 5]

random.shuffle(my_list)

print(my_list)

# [5, 3, 1, 2, 4]
# [5, 2, 4, 3, 1]
[5, 3, 1, 2, 4]

էլի լիքը կան, կարող եք գտնել այստեղ՝ https://docs.python.org/3/py-modindex.html

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
import antigravity # colabում չի աշխատի
from __future__ import braces # {

# for i in range(1,2):
#   pass
  Input In [72]
    from __future__ import braces # {
    ^
SyntaxError: not a chance

not built in packages

https://pypi.org/ | conda (anaconda) | uv

pip = pip installs packages

tqdm

tqdm means “progress” in Arabic (taqadum, تقدّم) and is an abbreviation for “I love you so much” in Spanish (te quiero demasiado)

!pip install tqdm # pip install packages
ERROR: Invalid requirement: '#'
import time

for i in range(10):
    print(i)
    time.sleep(0.5) # slow code
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
import time

for i in range(30):
    if i % 5 == 0:
        print(f"արեցի {i} հատ")
    time.sleep(1)
արեցի 0 հատ
արեցի 5 հատ
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
Input In [2], in <cell line: 3>()
      4 if i % 5 == 0:
      5     print(f"արեցի {i} հատ")
----> 6 time.sleep(1)

KeyboardInterrupt: 
!pip install tqdm # pip -> Pip Installes Packages
Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (4.66.1)
# pip install tqdm
from tqdm import tqdm
for i in tqdm(range(15)):
    time.sleep(0.5)
  0%|          | 0/15 [00:00<?, ?it/s]100%|██████████| 15/15 [00:07<00:00,  1.95it/s]
100%|██████████| 15/15 [00:07<00:00,  1.95it/s]
# please ignore this cell
with open("music.txt", "w") as f:
    f.write("""Ծաղկած դաշտում նորից տեսա իմ յարին,
Իմ աննման , իմ գեղանի մարալին:
Վարդ էր ցանել մեր սիրո ճանապարհին,
Դրախտի մեջ շողշողում է իմ Փերին։
Դրախտի ալվան ծաղիկ է իմ փերին,
Անմահական նեկտար ունի շուրթերին:
Անցնում էի ծաղկադալար պուրակով,
Սիրտս լցված նրա սիրո կրակով,
Հնդստանը թեկուզ ման գաս ճրագով,
Միևնույն է աննման է իմ փերին։
Դրախտի ալվան ծաղիկ է իմ փերին,
Անմահական նեկտար ունի շուրթերին:
Աշուղ Անդրանիկն եմ՝միտքս վարարուն,
Յարիս սերը սրտիս խորքում մարմարում,
Ով յար չունի խեղճ ու մոլոր անճար է,
Իր աշուղով երջանիկ է իմ փերին։
Դրախտի ալվան ծաղիկ է իմ փերին,
Անմահական նեկտար ունի շուրթերին:""")

File I/O

սովորական ձև

PATH = 'music.txt'

f = open(PATH, mode="r") # open(PATH)
print(f)
<_io.TextIOWrapper name='music.txt' mode='r' encoding='UTF-8'>
print(f.read())

f.close()
Ծաղկած դաշտում նորից տեսա իմ յարին,
Իմ աննման , իմ գեղանի մարալին:
Վարդ էր ցանել մեր սիրո ճանապարհին,
Դրախտի մեջ շողշողում է իմ Փերին։
Դրախտի ալվան ծաղիկ է իմ փերին,
Անմահական նեկտար ունի շուրթերին:
Անցնում էի ծաղկադալար պուրակով,
Սիրտս լցված նրա սիրո կրակով,
Հնդստանը թեկուզ ման գաս ճրագով,
Միևնույն է աննման է իմ փերին։
Դրախտի ալվան ծաղիկ է իմ փերին,
Անմահական նեկտար ունի շուրթերին:
Աշուղ Անդրանիկն եմ՝միտքս վարարուն,
Յարիս սերը սրտիս խորքում մարմարում,
Ով յար չունի խեղճ ու մոլոր անճար է,
Իր աշուղով երջանիկ է իմ փերին։
Դրախտի ալվան ծաղիկ է իմ փերին,
Անմահական նեկտար ունի շուրթերին:
f = open(PATH, "r")

text = f.readlines()

print(text)
['Ծաղկած դաշտում նորից տեսա իմ յարին,\n', 'Իմ աննման , իմ գեղանի մարալին:\n', 'Վարդ էր ցանել մեր սիրո ճանապարհին,\n', 'Դրախտի մեջ շողշողում է իմ Փերին։\n', 'Դրախտի ալվան ծաղիկ է իմ փերին,\n', 'Անմահական նեկտար ունի շուրթերին:\n', 'Անցնում էի ծաղկադալար պուրակով,\n', 'Սիրտս լցված նրա սիրո կրակով,\n', 'Հնդստանը թեկուզ ման գաս ճրագով,\n', 'Միևնույն է աննման է իմ փերին։\n', 'Դրախտի ալվան ծաղիկ է իմ փերին,\n', 'Անմահական նեկտար ունի շուրթերին:\n', 'Աշուղ Անդրանիկն եմ՝միտքս վարարուն,\n', 'Յարիս սերը սրտիս խորքում մարմարում,\n', 'Ով յար չունի խեղճ ու մոլոր անճար է,\n', 'Իր աշուղով երջանիկ է իմ փերին։\n', 'Դրախտի ալվան ծաղիկ է իմ փերին,\n', 'Անմահական նեկտար ունի շուրթերին:']
f = open(PATH)

print(f.closed)
f.close() # շառից փորձանքից հեռու, պետքա միշտ փակենք ֆայլը
print(f.closed)
False
True
help(open)
Help on built-in function open in module io:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError upon failure.
    
    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)
    
    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode.  Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:
    
    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================
    
    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.
    
    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.
    
    'U' mode is deprecated and will raise an exception in future versions
    of Python.  It has no effect in Python 3.  Use newline to control
    universal newlines mode.
    
    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer.  When no buffering argument is
    given, the default buffering policy works as follows:
    
    * Binary files are buffered in fixed-size chunks; the size of the buffer
      is chosen using a heuristic trying to determine the underlying device's
      "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
      On many systems, the buffer will typically be 4096 or 8192 bytes long.
    
    * "Interactive" text files (files for which isatty() returns True)
      use line buffering.  Other text files use the policy described above
      for binary files.
    
    encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent, but any encoding supported by Python can be
    passed.  See the codecs module for the list of supported encodings.
    
    errors is an optional string that specifies how encoding errors are to
    be handled---this argument should not be used in binary mode. Pass
    'strict' to raise a ValueError exception if there is an encoding error
    (the default of None has the same effect), or pass 'ignore' to ignore
    errors. (Note that ignoring encoding errors can lead to data loss.)
    See the documentation for codecs.register or run 'help(codecs.Codec)'
    for a list of the permitted encoding error strings.
    
    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If closefd is False, the underlying file descriptor will be kept open
    when the file is closed. This does not work when a file name is given
    and must be True in that case.
    
    A custom opener can be used by passing a callable as *opener*. The
    underlying file descriptor for the file object is then obtained by
    calling *opener* with (*file*, *flags*). *opener* must return an open
    file descriptor (passing os.open as *opener* results in functionality
    similar to passing None).
    
    open() returns a file object whose type depends on the mode, and
    through which the standard file operations such as reading and writing
    are performed. When open() is used to open a file in a text mode ('w',
    'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
    a file in a binary mode, the returned class varies: in read binary
    mode, it returns a BufferedReader; in write binary and append binary
    modes, it returns a BufferedWriter, and in read/write mode, it returns
    a BufferedRandom.
    
    It is also possible to use a string or bytearray as a file for both
    reading and writing. For strings StringIO can be used like a file
    opened in a text mode, and for bytes a BytesIO can be used like a file
    opened in a binary mode.
# read and write
PATH = 'music.txt'

f = open(PATH, mode="r") # open(PATH)
print(f)

print(f.write("a"))
<_io.TextIOWrapper name='music.txt' mode='r' encoding='UTF-8'>
---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
Input In [12], in <cell line: 6>()
      3 f = open(PATH, mode="r") # open(PATH)
      4 print(f)
----> 6 print(f.write("a"))

UnsupportedOperation: not writable
f = open(PATH, mode="w") # write, read

f.write('a')
# f.read()#d()

f.close()
---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
Input In [15], in <cell line: 4>()
      1 f = open(PATH, mode="w") # write, read
      3 # f.write('a')
----> 4 f.read()#d()
      6 f.close()

UnsupportedOperation: not readable
f = open(PATH, mode="a") # write, read, append

f.write('123456')
# f.read()#d()

f.close()
Character Meaning
--------- ---------------------------------------------------------------
'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'a'       open for writing, appending to the end of the file if it exists
'b'       binary mode
't'       text mode (default)
'+'       open a disk file for updating (reading and writing)
'U'       universal newline mode (deprecated)

with

f = open(PATH, "r")
print(f.closed)
f.close()
print(f.closed)
False
True
with open(PATH, "r") as f: #, ... open(..,) as f2
    print(f.read())
    # f.write("a")
    print(f.closed)
    
    
    # f.close()
    
print(f.closed)
BB123456
False
True
with open(PATH, "r") as f:
    print(f.read())
    # f.write("a")
    print(f.closed)
# f.closed
print(f.closed)

JSON

import json # JavaScript Object Notation

example_data = {
    "name": "Bob",
    "age": 17,
    "skills": ["չինգաչունգ", "բլոտ", "նարդի"]
}

with open('data.json', 'w') as f:
    # json.dump(example_data, f)
    json.dump(example_data, f, indent=4)  # indent - գեղեցիկ ձևով գրելու համար
import json

with open('data.json', 'r') as f:
    data = json.load(f)

print("Name:", data["name"])
print("Age:", data["age"])
print("Skills:", data["skills"])
Name: Bob
Age: 17
Skills: ['չինգաչունգ', 'բլոտ', 'նարդի']

Pickle Files

The pickle module is used to serialize and deserialize Python objects. Serialization is the process of converting a Python object into a byte stream, and deserialization is the reverse process.

Why Use Pickle?

  • Save Python objects to a file for later use.
  • Transfer Python objects between programs or over a network.

image.png

image.png
import pickle

# Example: Saving data to a pickle file
data = ["panir", 509]

with open('data.pkl', 'wb') as f:  # 'wb' mode is for writing binary
    pickle.dump(data, f)

print("Data has been serialized and saved to 'data.pkl'.")
Data has been serialized and saved to 'data.pkl'.
import pickle

# Example: Loading data xfrom a pickle file
with open('data.pkl', 'rb') as file:  # 'rb' mode is for reading binary
    loaded_data = pickle.load(file)

print("Data has been deserialized:", loaded_data)
Data has been deserialized: ['panir', 509]

🏡Տնային

https://shudadi-shudada.notion.site/File-Organizer-1b58d0610fed81a98703c4f6c4af9cb5

🎲 9

Flag Counter