Python basic grammar note (4)

at first

This is a memo while studying python I will add various things in the future

File operations and system

File creation

# Open and close the file
f = open('text.text', 'w')
f.write('Text\n')
f.close()

Open the file with the with statement

with open('text.text', 'w') as f:
    f.write('Test\n')

Read file

# By chunk
with open('text.text', 'r') as f:
    while True:
        chunk = 2
        line = f.read(chunk)
        print(line)
        if not line:
            break
         
>>Te
>>st

 (Test is entered in the text.text file)

Use seek to move

s = """\
AAA
BBB
CCC
"""

with open('text.text', 'r') as f:
    print(f.tell())
    print(f.read(1))
    f.seek(5)

>>>0
>>>A

Write / read mode


s = """\
AAA
BBB
CCC
EEE
"""

with open('text.text', 'r+') as f:
    print(f.read())
    f.seek(0)
    f.write(s)

# Also written to the text.text file
AAA
BBB
CCC
EEE

template

import string

s = """\

Hi $name

$contents

Have a good day

"""

t = string.Template(s)
contents = t.substitute(name='Mike', contents='How are you')
print(contents)

>>>Hi Mike
>>>How are you
>>>Have a good day

Write and read to CSV file

import csv

with open('text.csv,', 'w') as csv_file:
    fieldnames = ['Name', 'Count']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Name': 'A', 'Count': 1})
    writer.writerow({'Name': 'B', 'Count': 2})

with open('test.csv', 'r') as csv_file:
    reader = csv.DictReader(csv)
    for row in reader:
        print(row['Name'], row['Count'])


File operations

import os
import pathlib
import glob
import shutil

# Whether there is text.text
print(os.path.exists('text.text'))
>>>True

# Check if it is a file
print(os.path.isfile('text.text'))

# Is it a directory?
print(print(os.path.isdir('sample_codes')))

# Rename the file
os.rename('text.text', 'renamed.text')

# Simulink link
os.symlink('renamed.text', 'symlink.txt')

# Create a directory
os.mkdir('test.dir')

# Erase the directory
os.rmdir('test.dir')

# Create a file
pathlib.Path('empty.txt').touch()

# Erase files
os.remove('empty.txt')

# View the list of directories
os.mkdir('test_dir')
os.mkdir('test_dir/test_dir2')
print(os.listdir('test_dir'))

# What kind of files are there
pathlib.Path('test_dir/test_dir2/empty.txt').touch()

# View all files
print(glob.glob('test_dir/test_dir2/*'))

# make a copy
shutil.copy('test_dir/test_dir2/empty.txt','test_dir/test_dir2/empty2.txt')

# Erase all directories
shutil.rmtree('test_dir')

# I want to know the location of the directory
print(os.getcwd())

Compress and decompress tarfile

import tarfile

with tarfile.open('test.tar.gz', 'w:gz') as tr:
    tr.add('test_dir')

# Deploy with python
with tarfile.open('test.tar.gz', 'r:gz') as tr:
    tr.extractall(path='test_dir')

# If you want to see only the contents
with tarfile.open('test.tar.gz', 'r:gz') as tr:
    with tr.extractall('test_dir/sub_dir/sub_test.txt') as f:
        print(f.read())

Compress and decompress zipfile

import glob
import zipfile


with zipfile.ZipFile('text.zip', 'w') as z:
    z.write('test_dir')
    z.write('test_dir/text.txt')
    for f in glob.glob('text_dir/**', recursive=True):
        z.write(f)

with zipfile.ZipFile('test.zip', 'r') as z:
    z.extractall('zzz2')
    with z.open('text_dir/text.txt') as f:
        print(f.read())

What is tempfile

import tempfile

# Temporarily generate a file
with tempfile.TemporaryFile(mode='w+') as t:
    t.write('hello')
    t.seek(0)
    print(t.read())

# Actually create the file
with tempfile.NamedTemporaryFile(delete=False) as t:
    print(t.name)
    with open(t.name, '+w') as f:
        f.write('test\n')
        f.seek(0)
        print(f.read())

with tempfile.TemporaryDirectory() as td:
    print(td)

temp_dir = tempfile.mkdtemp()
print(temp_dir)

Execute command in subprocess

import subprocess

subprocess.run(['ls', '-al'])

What is datetime

import datetime

now = datetime.datetime.now()
print(now)
print(now.isoformat())
print(now.strftime('%d/%m/%y'))

today = datetime.date.today()
print(today.isoformat())
print(today.strftime('%d/%m/%y'))

Recommended Posts

Python basic grammar note (4)
Python basic grammar note (3)
Python3 basic grammar
Python basic grammar / algorithm
Python basic grammar (miscellaneous)
Python basic grammar memo
Basic Python 3 grammar (some Python iterations)
Python Basic Grammar Memo (Part 1)
Note: Python
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Basic Python grammar for beginners
Python note
I learned Python basic grammar
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
Java and Python basic grammar comparison
Basic grammar of Python3 system (dictionary)
Note: Python Decorator
Python programming note
[Python] Learning Note 1
python grammar check
Python study note_004
Basic Python writing
Python study note_003
Python grammar notes
[Note] openCV + python
RF Python Basic_02
Python beginner's note
[Basic grammar] Differences between Ruby / Python / PHP
[Python] I personally summarized the basic grammar.
Basic grammar of Python3 system (character string)
Basic grammar of Python3 series (list, tuple)
Basic grammar of Python3 system (included notation)
Python basic course (12 functions)
Python I'm also basic
Python Basic Course (7 Dictionary)
[Note] future sentence ~ Python ~
Python basic course (2 Python installation)
[Note] File reading ~ Python ~
[Go] Basic grammar ② Statement
Python ~ Grammar speed learning ~
[python] class basic methods
Python Basic Course (11 exceptions)
Python3 cheat sheet (basic)
Python Basic Course (Introduction)
Python basic memorandum part 2
python basic on windows ②
Python basic memo --Part 2
VBA user tried using Python / R: basic grammar
Note to daemonize python
Note: python Skeleton Nya
Python basic course (13 classes)
Basic Python command memo
Basic knowledge of Python
(Note) Basic statistics on Python & Pandas on IBM DSX
Python Tkinter Primer Note
OpenCV basic code (python)
Python basic memo --Part 1
python memorandum super basic
Python basic course (8 branches)