Opensourcetechブログ

OpensourcetechによるNGINX/Kubernetes/Zabbix/Neo4j/Linuxなどオープンソース技術に関するブログです。

Pythonの関数作成・ファイル書込/追記/読込の練習


LinuCエヴァンジェリストの鯨井貴博@opensourcetechです。

ちょっとPythonの練習をしたんで、忘れないようにメモ。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#read librariese
import sys,time,subprocess

#defined & execute time() function
def time():
    cmd = subprocess.run(["date +%M%S"], stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
    date = print(cmd.stdout.decode("utf8"),end="")
t = time()

#write "ABC\n" to test.txt
with open('/home/takahiro/test.txt', 'w') as f:
    f.write("ABC\n")

#open test.txt & print first byte
file = open('/home/takahiro/test.txt', 'r')
string = file.read()
file.close()
print (string[0])

#open test.txt & print second byte
file = open('/home/takahiro/test.txt', 'r')
string = file.read()
file.close()
print (string[1])

#open test.txt & print third byte
file = open('/home/takahiro/test.txt', 'r')
string = file.read()
file.close()
print (string[2])

#add "abc\n" to test.txt
with open('/home/takahiro/test.txt', 'a') as f:
    f.write("abc\n")

#open test.txt & print
file = open('/home/takahiro/test.txt', 'r')
string = file.read()
file.close()
print (string)



実行権限を付与します。

takahiro@ubuntu2004server:~$ chmod +x time.py
takahiro@ubuntu2004server:~$ ls -l time.py
-rwxrwxr-x 1 takahiro takahiro 1006 Jul 16 12:12 time.py
takahiro@ubuntu2004server:~$ date
Thu 16 Jul 2020 12:20:28 PM UTC



出力結果は、以下。
※最終行には、改行があります。

takahiro@ubuntu2004server:~$ ./time.py
1950
A
B
C
ABC
abc

Opensourcetech by Takahiro Kujirai