Category Archives: python

「python」2つの日付の日数を数える方法

pythonコード
#!/usr/bin/python
import time
import sys
def dateinput():
date = raw_input(‘please input the first date: ‘)
return date
def datetrans(tdate):
spdate = tdate.replace(“/”,”-“)
try:
datesec = time.strptime(spdate,’%Y-%m-%d’)
except ValueError:
print “%s is not a rightful date!!” % tdate
sys.exit(1)
return time.mktime(datesec)
def daysdiff(d1,d2):
daysec = 24 * 60 * 60
return int(( d1 – d2 )/daysec)
date1 = dateinput()
date2 = dateinput()
date1sec = datetrans(date1)
date2sec = datetrans(date2)
print “The number of days between two dates is: “,daysdiff(date1sec,date2sec

「Python」8桁のパスワードを生成するサンプルコード

pythonコード
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import string
#方法1
seed = “1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-”
sa = []
for i in range(8):
sa.append(random.choice(seed))
salt = ”.join(sa)
print salt
#方法2
salt = ”.join(random.sample(string.ascii_letters + string.digits, 8))
print salt

「Python」日付フォーマット(datetime)のサンプルコード

サンプルコード
import time
print(time.strftime(“%Y-%m-%d %H:%M:%S”), time.localtime())

「python入門」テキストファイルにパスワードを生成するコード

pythonコード
#!/usr/bin/python
import string
letters = string.letters + string.digits + string.punctuation
length = len(letters)
fwrite = open(“/tmp/generatepwd.txt”,”wt”)
fread = open(“/tmp/generatepwd.txt”,”r”)
for num in xrange(8):
for times in xrange(length**num):
line=fread.read(num+1).rstrip()
for letter in letters:
fwrite.write(line + letter + “\n”)
fwrite.flush()
fwrite.close()
fread.close()

「python」zipファイルを読むサンプルコード

pythonコード
#!/usr/bin/env python
import zipfile
z = zipfile.ZipFile(“test.zip”,”r”)
for filename in z.namelist():
print ‘File:’,filename,
bytes = z.read(filename)
print ‘has’,len(bytes),’bytes’

「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