[python] 我的第一个python脚本
很丑陋,但是是我写的第一个Python程序。
想学习下python,于是将python.cn上的邮件列表存档下载下来,想用zcat将它们合并成一个文件,以便用mutt来观看存档,结果发现文件名是类似于2004-September.txt.gz这种结构,如果强行将它们合并的话,时间顺序就会不正确,应为这种文件名不会按照正确的时间来排序。
于是想到将月份由名称改成数字,这样可以解决文件名排序问题,昨天才看python,但是正好动一下手,解决这个"实际"问题 :-)
再次申明:很丑陋,但是完成了我的"实际需求"
想学习下python,于是将python.cn上的邮件列表存档下载下来,想用zcat将它们合并成一个文件,以便用mutt来观看存档,结果发现文件名是类似于2004-September.txt.gz这种结构,如果强行将它们合并的话,时间顺序就会不正确,应为这种文件名不会按照正确的时间来排序。
于是想到将月份由名称改成数字,这样可以解决文件名排序问题,昨天才看python,但是正好动一下手,解决这个"实际"问题 :-)
再次申明:很丑陋,但是完成了我的"实际需求"
-
#!/usr/bin/python
# coding: utf-8
# filename name_convert.py
import sys, os, string, re
def monthConvert(name):
""" monthConvert:Convert full month name to number.
Return a month as a decimal number
if Param is not a full month name, then return None """
month = {"January": "01",\
" February":"02",\
"March":"03 ",\
"April" :"04",\
" May":"05",\
"June":"06 ",\
"July": "07",\
" August":"08",\
"September":"09 ",\
"October" :"10",\
" November":"11",\
"December":"12 "}
name = name.capitalize()
try:
if month[name]:
return month[name]
except:
#print monthConvert.__doc__
return
def convertName(filename):
"""convertName: Convert full month name in filename to number.
Return new filename, month name is replaced by month number
if file name is not like -monthname.txt.gz, then return None """
if re.search('.txt.gz' ,filename):
newName = None
m = re.findall('-[a-zA-Z]+',filename)
for j in m:
monthName=j.strip('-')
monthNumber = monthConvert(monthName)
if monthNumber != None:
if newName != None:
newName = newName.replace(monthName,monthNumber)
else:
newName = filename.replace(monthName,monthNumber)
return newName
if __name__ == "__main__":
for i in os.listdir('.'):
newName = convertName(i)
if newName != None:
os.rename(i,newName)
评论