Category Archives: python

「Python」CSVの読み書きサンプルコード

pythonコード
import csv
for line in open(“cftdemo.csv”):
name,age,address = line.split(“,”)
name = name.strip(‘ \t\r\n’);
age = age.strip(‘ \t\r\n’);
address = birthday.strip(‘ \t\r\n’);
print (name + ‘\t’ + age + ‘\t’ + address)

「python」文字列をファイルに保存するコード

pythonコード
def save(filename, contents):
fh = open(filename, ‘w’)
fh.write(contents)
fh.close()
save(‘file.name’, ‘sample ‘)

「python」ファイルやフォルダーを削除するコード

サンプルコード
#!d:\python27\python.exe
# -*- coding: utf-8 -*-

import os
import re

from os import path
from shutil import rmtree

DEL_DIRS = None
DEL_FILES = r'(.+?\.pyc$|.+?\.pyo$|.+?\.log$)’

def del_dir(p):
“””Delete a directory.”””
if path.isdir(p):
rmtree(p)
print(‘D : %s’ % p)

def del_file(p):
“””Delete a file.”””
if path.isfile(p):
os.remove(p)
print(‘F : %s’ % p)

def gen_deletions(directory, del_dirs=DEL_DIRS, del_files=DEL_FILES):
“””Generate deletions.”””
patt_dirs = None if del_dirs == None else re.compile(del_dirs)
patt_files = None if del_files == None else re.compile(del_files)

for root, dirs, files in os.walk(directory):
if patt_dirs:
for d in dirs:
if patt_dirs.match(d):
yield path.join(root, d)
if patt_files:
for f in files:
if patt_files.match(f):
yield path.join(root, f)

def confirm_deletions(directory):
import Tkinter
import tkMessageBox

root = Tkinter.Tk()
root.withdraw()
res = tkMessageBox.askokcancel(“Confirm deletions?”,
“Do you really wish to delete?\n\n”
“Working directory:\n%s\n\n”
“Delete conditions:\n(D)%s\n(F)%s”
% (directory, DEL_DIRS, DEL_FILES))
if res:
print(‘Processing…’)
m, n = 0, 0
for p in gen_deletions(directory):
if path.isdir(p):
del_dir(p)
m += 1
elif path.isfile(p):
del_file(p)
n += 1
print(‘Clean %d dirs and %d files.’ % (m, n))
root.destroy()
else:
print(‘Canceled.’)
root.destroy()

root.mainloop()

if __name__ == ‘__main__’:
import sys
argv = sys.argv
directory = argv[1] if len(argv) >= 2 else os.getcwd()
confirm_deletions(directory)
# import subprocess
# subprocess.call(“pause”, shell=True)

「Python」テキストファイルの読み込みを行う方法まとめ

方法1
f = open(“zhang.txt”)
line = f.readline()
while line:
print line,
# print(line, end = ”)
line = f.readline()
f.close()

方法2
for line in open(“changfa.txt”):
print line,

方法3
f = open(“d:\\infodemo.txt”,”r”)
lines = f.readlines()
for line in lines
print line

「Python入門」文字列を扱うstring.Templateの使い方

pythonコード
# -*- coding: utf-8 -*-
import string

t = string.Template(‘$var’)
print(t.pattern.pattern)

class DemoTemplate(string.Template):
delimiter = ‘{{‘
pattern = r””’
\{\{(?:
(?P<escaped>\{\{) | # Escape sequence of two delimiters
(?P<named>[_a-z][_a-z0-9]*)\}\} | # delimiter and a Python identifier
{(?P<braced>[_a-z][_a-z0-9]*)}\}\} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
”’

t2 = DemoTemplate(””’
{{{{
{{var}}
”’)

print(‘MATCHES: ‘, t2.pattern.findall(t2.template))
print(‘SUBSTITUTED: ‘, t2.safe_substitute(var=’replacement’))

出力結果
\$(?:
(?P<escaped>\$) | # Escape sequence of two delimiters
(?P<named>[_a-z][_a-z0-9]*) | # delimiter and a Python identifier
{(?P<braced>[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)

MATCHES: [(‘{{‘, ”, ”, ”), (”, ‘var’, ”, ”)]
SUBSTITUTED:
{{
replacement

「python入門」split関数で文字列を分割するサンプルコード

サンプルコード1:
>>> str = ‘http://oosa.cft.sample.com/pdf/prepareinfo.pdf’
>>> print str.split()
[‘http://oosa.cft.sample.com/pdf/prepareinfo.pdf’]
>>> print str.split(‘/’)
[‘http:’, ”, ‘oosa.cft.sample.com’, ‘pdf’, ‘prepareinfo.pdf’]
>>> print str.split(‘/’)[-1]
prepareinfo.pdf
>>> print str.split(‘/’)[-1].split(‘.’)[0]
prepareinfo
>>>

サンプルコード2:
name = str[str.rfind(“/”)+1:str.rfind(“.”)]

Pythonでファイルやディレクトリを削除するサンプルコード

pythonコード:
class Deleter():
def __init__(self, ToPrint=True, Logger=None):
self.Logger = Logger
self.ToPrint = ToPrint
return

def Log(self, Str):
if self.Logger:
self.Logger.Log(Str)
if self.ToPrint:
print Str
return

## フォルダーを削除
# @param FolderName folder to delete
#<br/>
#Example:
#<pre>
# T = Common()
# FolderName = r’Temp’
# T.DeleteFolder(FolderName)
#</pre>
def DeleteFolder(self, FolderName):
””’delete files and folders”’
for Item in os.listdir(FolderName):
TempPath = os.path.join(FolderName, Item)
if os.path.isfile(TempPath):
self.DeleteFile(TempPath)
pass
elif os.path.isdir(TempPath):
self.DeleteFolder(TempPath)
pass
else:
self.Log(“Not a file or folder: %s” % (FolderName))
pass
pass

try:
os.rmdir(FolderName)
self.Log(“Folder deleted: %s” % (FolderName))
except:
self.Log(“Failed to delete folder: %s” % (FolderName))
pass

return

## ファイルを削除
# @param FileName file to delete
#<br/>
#Example:
#<pre>
# T = Common()
# FolderName = r’TempFile.txt’
# T.DeleteFile(FileName)
#</pre>
def DeleteFile(self, FileName):
try:
os.remove(FileName)
self.Log(“File deleted: %s” % (FileName))
except:
self.Log(“Failed to delete file: %s” % (FileName))
pass
return

## フォルダー一覧を削除
# @param FolderList a list of folder to delete
#<br/>
#Example:
#<pre>
# T = Common()
# FolderNameList = [r’Temp1′, r’Temp2′]
# T.DeleteFolders(FolderNameList)
#</pre>
def DeleteFolders(self, FolderNameList):
for FolderName in FolderNameList:
self.DeleteFolder(FolderName)
return

##ファイルリストを削除
# @param FolderList a list of files to delete
#<br/>
#Example:
#<pre>
# T = Common()
# FolderNameList = [r’Temp1.txt’, r’Temp2.txt’]
# T.DeleteFiles(FileNameList)
#</pre>
def DeleteFiles(self, FileNameList):
for FileName in FileNameList:
self.DeleteFile(FileName)
return

Op = Deleter()
Op.DeleteFile(‘pythsample.txt’)
# Failed to delete file: pythsample.txt

python開発–matplotlibで画像を読み取り、表示する

1.画像を表示
import matplotlib.pyplot as plt
import matplotlib.image as mpimg # mpimg
import numpy as np

ctimg = mpimg.imread(‘jiken.png’)
ctimg.shape #(512, 512, 3)

plt.imshow(ctimg)
plt.axis(‘off’)
plt.show()
2.rgb2grayを操作
def rgb2gray(rgb):
return np.dot(rgb[…,:3], [0.299, 0.587, 0.114])

gray = rgb2gray(ctimg)
plt.imshow(gray, cmap=’Greys_r’)
plt.axis(‘off’)
plt.show()

3.画像を圧縮
from scipy import misc
ctimg_new_sz = misc.imresize(ctimg, 0.5)
plt.imshow(ctimg_new_sz)
plt.axis(‘off’)
plt.show()

4.画像を保存
方法1
plt.imshow(ctimg_new_sz)
plt.axis(‘off’)
plt.savefig(‘ctimg_new_sz.png’)

方法2
from scipy import misc
misc.imsave(‘ctimg_new_sz.png’, ctimg_new_sz)

方法3
np.save(‘ctimg_new_sz’, ctimg_new_sz)
img = np.load(‘ctimg_new_sz.npy’)

pythonでmac物理アドレスを取得する

方法1
>>> import uuid
>>> node = uuid.getnode()
>>> mac = uuid.UUID(int=node)
>>> addr = mac.hex[-12:]
>>> addr

方法2
#!/bin/python

import os
import re

def GetMacAddressFun():
if os.name == ‘nt’:
try:
ret = ”
CmdLine = ‘ipconfig /all’
r = os.popen(CmdLine).read()
if r:
L = re.findall(‘Physical Address.*?([0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2})’, r)
if len(L) > 0:
ret = L[0]
except:
pass

elif os.name == “posix”:
try:
ret = ”
CmdLine = ‘ifconfig’
r = os.popen(CmdLine).read()
if r:
L = re.findall(‘HWaddr.*?([0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2})’, r)
if len(L) > 0:
ret = L[0]
except:
pass
else:
pass
return ret

if __name__ == ‘__main__’:
mac = GetMacAddressFun()
print mac
m=raw_input()

Pythonでバイナリファイルを読み書き操作

方法1
opfile=open(‘d:\\t’,’rb’)
s=opfile.read(1)
byte=ord(s)
print hex(byte)

方法2
import struct
opfile=open(‘d:\\t’,’rb’).read(1)
print struct.unpack(‘c’,opfile)
print struct.unpack(‘b’,opfile)