16. Files - MantsSk/CA_PTUA14 GitHub Wiki

Files and folders (os module)

import os

Get current catalog:

print(os.getcwd())

Change current catalog:

os.chdir('C:\\Users\\Donoras\\Desktop')
print(os.getcwd())

# C:\Users\Donoras\Desktop

Get files and folders in current folder

print(os.listdir())

# ['Demo katalogas', 'paveikslelis.jpg', 'tekstas.txt']

Create new folder:

os.mkdir("New folder")

or:

os.makedirs("Naujas katalogas/Katalogas kataloge")

print(os.listdir())

Get file/folder information:

print(os.stat("Demo Katalogas"))

or:

print(os.stat("naujas_tekstas.txt"))

# os.stat_result(st_mode=33206,
# st_ino=11258999068714091, st_dev=987816996,
# st_nlink=1, st_uid=0, st_gid=0, st_size=279,
# st_atime=1553103727, st_mtime=1553072965,
# st_ctime=1553101362)

Get file size:

print(os.stat("naujas_tekstas.txt").st_size)

# 279 (baitais)

Get last file modify date:

print(os.stat("naujas_tekstas.txt").st_mtime)

# 1553072965.1983721

Change timestamp to human readable format:

from datetime import datetime
data = os.stat("naujas_tekstas.txt").st_mtime
print(datetime.fromtimestamp(data))

# 2019-03-20 11:09:25.198372

Create and read text files

Create text file: (file gets created if it doesn't exist)

with open("failas.txt", 'w') as failas:
    failas.write("Sveikas, pasauli!")
#Sveikas, pasauli!

or:

failas = open("failas.txt", 'w')
failas.write("Sveikas, pasauli!")
failas.close()

Read file:

with open("failas.txt", 'r') as failas:
    print(failas.read())

# Sveikas, pasauli!

Read and write at the same time:

with open("failas.txt", 'r+') as failas:
    print(failas.read())
    failas.write("Labas rytas, pasauli!")

# Sveikas, pasauli!

with open("failas.txt", 'r') as failas:
    print(failas.read())

# Sveikas, pasauli!Labas rytas, pasauli!

Write to file with Lithuanian letters:

with open("failas.txt", 'w', encoding="utf-8") as failas:
    failas.write("Čia yra pirmas failo sakinys")
# Čia yra pirmas failo sakinys

Read from file:

with open("failas.txt", 'r') as failas:
    print(failas.read())
# ÄŒia yra pirmas failo sakinys

with open("failas.txt", 'r', encoding="utf-8") as failas:
    print(failas.read())

# Čia yra pirmas failo sakinys

Append text:

Problem:

with open("failas.txt", 'w', encoding="utf-8") as failas:
    failas.write("Čia yra pirmas sakinys \n")

with open("failas.txt", 'w', encoding="utf-8") as failas:
    failas.write("Čia yra antras sakinys \n")
# Čia yra antras sakinys

Solution:

with open("failas.txt", 'a', encoding="utf-8") as failas:
    failas.write("Čia yra pirmas sakinys \n")

with open("failas.txt", 'a', encoding="utf-8") as failas:
    failas.write("Čia yra antras sakinys \n")
# Čia yra pirmas sakinys

# Čia yra antras sakinys

Overwrite text in a specific location:

with open("failas.txt", 'w', encoding="utf-8") as failas:
    failas.write("Test")
    failas.write("Test")
# TestTest

with open("failas.txt", 'w', encoding="utf-8") as failas:
    failas.write("Test")
    failas.seek(0)
    failas.write("BE")
# BEst

Read one line at a time:

Čia yra pirmas sakinys
Čia yra antras sakinys
Čia yra trečias sakinys
Čia yra ketvirtas sakinys
Čia yra penktas sakinys
Čia yra šeštas sakinys
Čia yra septintas sakinys
Čia yra aštuntas sakinys
Čia yra devintas sakinys
Čia yra dešimtas sakinys
with open("failas.txt", 'r', encoding="utf-8") as failas:
    print(failas.readline())
    print(failas.readline())
    print(failas.readline())

# Čia yra pirmas sakinys
# Čia yra antras sakinys
# Čia yra trečias sakinys

or:

with open("failas.txt", 'r', encoding="utf-8") as failas:
    print(failas.readlines())

# ['Čia yra pirmas sakinys \n', 'Čia yra antras sakinys \n', 'Čia
# yra trečias sakinys \n', 'Čia yra ketvirtas sakinys \n', 'Čia yra
# penktas sakinys \n', 'Čia yra šeštas sakinys \n', 'Čia yra septintas
# sakinys \n', 'Čia yra aštuntas sakinys \n', 'Čia yra devintas sakinys \
# n', 'Čia yra dešimtas sakinys \n']

Iterate through lines in a file:

with open("failas.txt", 'r', encoding="utf-8") as failas:
    for eilute in failas:
        print(eilute)

# Čia yra pirmas sakinys

# Čia yra antras sakinys

# Čia yra trečias sakinys

# Čia yra ketvirtas sakinys

Remove new line at the end of the line:

with open("failas.txt", 'r', encoding="utf-8") as failas:
    for eilute in failas:
        print(eilute.strip())

# Čia yra pirmas sakinys
# Čia yra antras sakinys
# Čia yra trečias sakinys
# Čia yra ketvirtas sakinys
# Čia yra penktas sakinys
# Čia yra šeštas sakinys
# Čia yra septintas sakinys
# .............

Read specific number of symbols:

with open("failas.txt", 'r', encoding="utf-8") as failas:
    print(failas.read(100))

# Čia yra pirmas sakinys
# Čia yra antras sakinys
# Čia yra trečias sakinys
# Čia yra ketvirtas sakinys

print(failas.read(100))

# Čia yra penktas sakinys
# Čia yra šeštas sakinys
# Čia yra septintas sakinys
# Čia yra aštuntas sakinys

print(failas.read(100))

# Čia yra devintas sakinys
# Čia yra dešimtas sakinys

Copy data from one file to another:

with open("failas.txt", 'r') as r_failas:
    with open("failo_kopija.txt", 'w') as w_failas:
        for r_eilute in r_failas:
            w_failas.write(r_eilute)

Copying binary data:

Problem:

with open("logo.png", 'r') as r_failas:
    with open("logo_kopija.png", 'w') as w_failas:
        for r_eilute in r_failas:
            w_failas.write(r_eilute)

# UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 65: character maps to <undefined>

Solution:

with open("logo.png", 'rb') as r_failas:
    with open("logo_kopija.png", 'wb') as w_failas:
        for r_eilute in r_failas:
            w_failas.write(r_eilute)

(gauname paveikslėlio failo kopiją)

Save variables to file (module pickle)

Write to file:

import pickle

a = 1024

with open("a.pkl", "wb") as pickle_out:
    pickle.dump(a, pickle_out)

Read:

import pickle

with open("a.pkl", "rb") as pickle_in:
    naujas_a = pickle.load(pickle_in)

print(naujas_a)

# 1024

Write to file:

import pickle

zodynas = {1:"Pirmas", 2:"Antras", 3:"Trečias"}

with open("zodynas.pkl", "wb") as pickle_out:
    pickle.dump(zodynas, pickle_out)

Read:

import pickle

with open("zodynas.pkl", "rb") as pickle_in:
    naujas_zodynas = pickle.load(pickle_in)

print(naujas_zodynas)

# {1: 'Pirmas', 2: 'Antras', 3: 'Trečias'}

Write multiple variables to file:

a = 10
b = 7
c = 23

with open("abc.pkl", "wb") as pickle_out:
    pickle.dump(a, pickle_out)
    pickle.dump(b, pickle_out)
    pickle.dump(c, pickle_out)

Read:

with open("abc.pkl", "rb") as pickle_in:
    nauja_a = pickle.load(pickle_in)
    nauja_b = pickle.load(pickle_in)
    nauja_c = pickle.load(pickle_in)

print(nauja_a)
print(nauja_b)
print(nauja_c)

# 10
# 7
# 23

or:

import pickle

with open("abc.pkl", "rb") as pickle_in:
    while True:
        try:
            print(pickle.load(pickle_in))
        except EOFError:
            break

# 10
# 7
# 23

Example:

import pickle

while True:
    veiksmas = int(input("Pasirinkite veiksmą: 1 - peržiūrėti, 2 - įrašyti, 3 - išeiti"))
    if veiksmas == 1:
        try:
            with open("zmones.pkl", 'rb') as failas:
                print(pickle.load(failas))
        except:
            print("Nėra tokio failo")
            with open("zmones.pkl", 'wb') as failas:
                zmones = []
                pickle.dump(zmones, failas)
    if veiksmas == 2:
        with open("zmones.pkl", 'rb') as failas:
            zmones = pickle.load(failas)
            vardas = input("Įveskite naują vardą")
            with open("zmones.pkl", 'wb') as failas:
                zmones.append(vardas)
                pickle.dump(zmones, failas)
    if veiksmas == 3:
        print("Programa baigta")
        break

Exercises

Exercise 1

Create a program that would:

* Create a file "Text.txt" and add a text provided below to it
* Read text from that file and just print it
* Append any text to the end of the file
* Add line numbers to every line in the file 
* Change "Beautiful is better than ugly." text to  "Gražu yra geriau nei bjauru."
* Print text from the file in reverse
* Print number of words, numbers, capital letters, lower letters in the file
* Copy the text from the file to a new file (text in the new file should be ALL CAPS)

Tekstas:

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!

Exercise 2

Create mini budgeting program:

  • Program should read a list of incomes/expenses from an already existing file. If file does not exist - just create an empty list
  • It should let users add income by entering positive numbers and expenses by entering negative numbers. Expenses and income should be saved to a list
  • It should be able to display all incomes and expenses and total sum
  • Program should be able finish and save the budget list to a pickle file for a later use

Tip:

import pickle

⚠️ **GitHub.com Fallback** ⚠️