0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python基本文法note(4)

Last updated at Posted at 2020-12-20

初めに

pythonを勉強中のメモです
色々今後追加していきます

ファイル操作とシステム

ファイルの作成

# ファイルを開いたら閉じる
f = open('text.text', 'w')
f.write('Text\n')
f.close()

withステートメントでファイルをopenする

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

ファイルの読み込み

# チャンクごと
with open('text.text', 'r') as f:
    while True:
        chunk = 2
        line = f.read(chunk)
        print(line)
        if not line:
            break
         
>>Te
>>st

(text.textファイルにTestと入力されている) 

seekを使って移動する

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

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

>>>0
>>>A

書き込み読み込みモード


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

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

# text.textファイルにも書き込まれた
AAA
BBB
CCC
EEE

テンプレート

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

CSVファイルへの書き込みと読み込み

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'])


ファイル操作

import os
import pathlib
import glob
import shutil

# text.textがあるかどうか
print(os.path.exists('text.text'))
>>>True

# ファイルなのか確認する
print(os.path.isfile('text.text'))

# ディレクトリなのか
print(print(os.path.isdir('sample_codes')))

# ファイルの名前を変える
os.rename('text.text', 'renamed.text')

# シムリンクにする
os.symlink('renamed.text', 'symlink.txt')

# ディレクトリを作成する
os.mkdir('test.dir')

# ディレクトリを消す
os.rmdir('test.dir')

# ファイルを作る
pathlib.Path('empty.txt').touch()

# ファイルを消す
os.remove('empty.txt')

# ディレクトリのリストを見る
os.mkdir('test_dir')
os.mkdir('test_dir/test_dir2')
print(os.listdir('test_dir'))

# どんなファイルがあるか
pathlib.Path('test_dir/test_dir2/empty.txt').touch()

# 全てのファイルを見る
print(glob.glob('test_dir/test_dir2/*'))

# コピーする
shutil.copy('test_dir/test_dir2/empty.txt','test_dir/test_dir2/empty2.txt')

# 全てのディレクトリを消す
shutil.rmtree('test_dir')

# ディレクトリの位置を知りたい
print(os.getcwd())

tarfileの圧縮展開

import tarfile

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

# pythonで展開する
with tarfile.open('test.tar.gz', 'r:gz') as tr:
    tr.extractall(path='test_dir')

# 中身だけ見たい場合
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())

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())

tempfileとは

import tempfile

# 一時的にファイルを生成する
with tempfile.TemporaryFile(mode='w+') as t:
    t.write('hello')
    t.seek(0)
    print(t.read())

# ファイルを実際に作成する
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)

subprocessでコマンドを実行する

import subprocess

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

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'))

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?