python os.path模块/Python os.listdir/字符串处理/python 时间datetime.datetime

来源:互联网 发布:2010年总决赛科比数据 编辑:程序博客网 时间:2024/05/22 12:43
1.1 python os.path模块

os.path.abspath(path) #返回绝对路径
os.path.basename(path) #返回文件名
os.path.commonprefix(list) #返回list(多个路径)中,所有path共有的最长的路径。
os.path.dirname(path) #返回文件路径
os.path.exists(path)  #路径存在则返回True,路径损坏返回False
os.path.lexists  #路径存在则返回True,路径损坏也返回True
os.path.expanduser(path)  #把path中包含的"~"和"~user"转换成用户目录
os.path.expandvars(path)  #根据环境变量的值替换path中包含的”$name”和”${name}”
os.path.getatime(path)  #返回最后一次进入此path的时间。
os.path.getmtime(path)  #返回在此path下最后一次修改的时间。
os.path.getctime(path)  #返回path的大小
os.path.getsize(path)  #返回文件大小,如果文件不存在就返回错误
os.path.isabs(path)  #判断是否为绝对路径
os.path.isfile(path)  #判断路径是否为文件
os.path.isdir(path)  #判断路径是否为目录
os.path.islink(path)  #判断路径是否为链接
os.path.ismount(path)  #判断路径是否为挂载点()
os.path.join(path1[, path2[, ...]])  #把目录和文件名合成一个路径
os.path.normcase(path)  #转换path的大小写和斜杠
os.path.normpath(path)  #规范path字符串形式
os.path.realpath(path)  #返回path的真实路径
os.path.relpath(path[, start])  #从start开始计算相对路径
os.path.samefile(path1, path2)  #判断目录或文件是否相同
os.path.sameopenfile(fp1, fp2)  #判断fp1和fp2是否指向同一文件
os.path.samestat(stat1, stat2)  #判断stat tuple stat1和stat2是否指向同一个文件
os.path.split(path)  #把路径分割成dirname和basename,返回一个元组
os.path.splitdrive(path)   #一般用在windows下,返回驱动器名和路径组成的元组
os.path.splitext(path)  #分割路径,返回路径名和文件扩展名的元组
os.path.splitunc(path)  #把路径分割为加载点与文件
os.path.walk(path, visit, arg)  #遍历path,进入每个目录都调用visit函数,visit函数必须有
3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有
文件名,args则为walk的第三个参数
os.path.supports_unicode_filenames  #设置是否支持unicode路径名

1.2 Python os.listdir


在Python os.listdir 中我们可以列出关于dir 里面的所有的相关文件与目录的具体操作方案的介绍,以及我们在实际如何用Python中的os.path.isfile()函数来判断相关路径是否为文件的操作方案,以下是文章的具体介绍。

Python判断是否为文件在Python os.listdir 函数判断某一路径是否为文件。其函数原型如下所示。

  1. os.path.isfile(path) 

其参数含义如下。path:要进行判断的路径。以下实例判断E:\book\temp是否为文件。

  1. >>> import os  
  2. >>> os.path.isfile('E:\\book\\temp')   

判断是否为文件

  1. False  

表示E:\book\temp不是文件列出目录中所有文件的方法

关键字:

  1. dirimport string, os, sys  
  2. dir = '/var' 
  3. print '----------- no sub dir'  
  4. files = os.listdir(dir)  
  5. for f in files:  
  6. print dir + os.sep + f  
  7. print '----------- all dir'  
  8. for root, dirs, files in os.walk(dir):  
  9. for name in files:  
  10. print os.path.join(root, name)   
前面的Python os.listdir 可以列出 dir 里面的所有文件和目录,但不包括子目录中的内容。os.walk 可以遍历下面的所有目录,包括子目录。

1.3 字符串处理

判断 – 通常返回一个bool值str.isalpha()是否只包含文字str.isdecimal()是否只包含数字(多语言数字)str.isdigit()是否只包含数字(0~9)str.isnumeric()是否只包含数字字符str.isalnum()是否只包含文字和数字str.isidentifier()是否是合法标识符str.islower()是否是小写str.isupper()是否全是大写str.istitle()是否每词首字母大写str.isprintable()是否只包含可打印字符str.isspace()是否只包含空白字符str.startswith(prefix[, start[, end]])是否以prefix开头str.endswith(suffix[, start[, end]])是否以suffix结尾修饰 – 通常返回一个修饰后的字符串str.capitalize()返回一个首字母大写的字符串str.title()返回每个词首字母大写的字符串str.expandtabs([tabsize])"\t"转换成空格str.upper()全转换成大写str.lower()全转换成小写str.ljust(width[, fillchar])左对齐,右填充str.rjust(width[, fillchar])右对齐,左填充str.center(width[, fillchar])居中,两边填充str.lstrip([chars])去除左空白或自定字符str.rstrip([chars])去除右空白或自定字符str.strip([chars])去除两边空白或自定字符str.swapcase()大小写互转str.zfill(width)左侧填充0到指定宽,一般用来修饰数字查找&&替换str.count(sub[, start[, end]])计算[start, end)间,sub出现次数str.find(sub[, start[, end]]) str.index(sub[, start[, end]]) str.rfind(sub[, start[, end]]) str.rindex(sub[, start[, end]]) str.replace(old, new[, count]) 拆分&&组合str.join(iterable) str.partition(sep) str.rpartition(sep) str.split([sep[, maxsplit]]) str.rsplit([sep[, maxsplit]]) str.splitlines([keepends]) 转换hex(x) int([number | string[, base]]) len(s) list([iterable]) oct(x) ord(c) repr(object) reversed(seq) str([object[, encoding[, errors]]]) 

↑TOP↑str.isalpha() – 是否只包含文字

代码结果print( "中国abc".isalpha() )Trueprint( " ".isalpha() )Falseprint( "123".isalpha() )Falseprint( "".isalpha() )False

↑TOP↑str.isdecimal() – 是否只包含十进制数字,包括多语言数字

代码结果print( "1234567890".isdecimal() )Trueprint( "\u0660".isdecimal() )Trueprint( "abc".isdecimal() )Falseprint( "".isdecimal() )False

关于其他语言的数字参见 http://www.fileformat.info/info/unicode/category/Nd/list.htm

↑TOP↑str.isdigit() – 是否只包含数字(0~9)

代码结果print( "1234567890".isdigit() )Trueprint( "\u0660".isdigit() )Trueprint( "abc".isdigit() )Falseprint( "".isdigit() )False

↑TOP↑str.isnumeric() – 是否只包含数字字符

代码结果print( "1234567890".isnumeric() )Trueprint( "\u2155".isnumeric() )Trueprint( "abc".isnumeric() )Falseprint( "".isnumeric() )False

关于数字字符参见 http://www.fileformat.info/info/unicode/category/No/list.htm

↑TOP↑str.isalnum() – 是否只包含文字和数字

代码结果print( "中国abc123456\u2155".isalnum() )Trueprint( " ".isalnum() )Falseprint( "\t".isalnum() )Falseprint( "".isalnum() )False

↑TOP↑str.isidentifier() – 是否是合法标识符

代码结果print( "if".isidentifier() )Trueprint( "中国".isidentifier() )Trueprint( "123".isidentifier() )Falseprint( "".isidentifier() )False

↑TOP↑str.islower() – 是否是小写

代码结果print( "abc".islower() )Trueprint( "aBc".islower() )Falseprint( "中国".islower() )Falseprint( "".islower() )False

↑TOP↑str.isupper() – 是否全是大写

代码结果print( "HELLO WORLD".istitle() )Trueprint( "Hello World".istitle() )Falseprint( "世界你好".istitle() )Falseprint( "".istitle() )False

↑TOP↑str.istitle() – 是否每词首字母大写

代码结果print( "Hello World".istitle() )Trueprint( "Hello world".istitle() )Falseprint( "hello world".istitle() )Falseprint( "".istitle() )False

↑TOP↑str.isprintable() – 是否只包含可打印字符

代码结果print( "a b".isprintable() )Trueprint( "".isprintable() )Trueprint( "abc\t".isprintable() )Falseprint( "abc\n".isprintable() )False

↑TOP↑str.isspace() – 是否只包含空白字符

代码结果print( " ".isspace() )Trueprint( "\t\n".isspace() )Trueprint( "a b".isspace() )Falseprint( "".isspace() )False

↑TOP↑str.startswith(prefix[, start[, end]]) – 是否以prefix开头

代码结果print( "中国人".startswith("中") )Trueprint( "中国人".startswith(("中国","我")) )True

↑TOP↑str.endswith(suffix[, start[, end]]) – 是否以suffix结尾

代码结果print( "中国人".endswith("人") )Trueprint( "中国人".endswith(("国人","我")) )True

↑TOP↑str.capitalize() – 返回一个首字母大写的字符串

代码print( "the first sentence. the second sentence.".capitalize() )结果The first sentence. the second sentence.

↑TOP↑str.title() – 返回每个词首字母大写的字符串

代码print( "this is a title".title() )结果This Is A Title

↑TOP↑str.expandtabs([tabsize]) – "\t"转换成空格

代码"\t".expandtabs(8)结果'        '

↑TOP↑str.upper() – 全转换成大写

代码print( "abc".upper() )结果ABC

↑TOP↑str.lower() – 全转换成小写

代码print( "ABC".upper() )结果abc

↑TOP↑str.ljust(width[, fillchar]) – 左对齐,右填充

代码print( "我".ljust(4,"们") )结果

我们们们

↑TOP↑str.rjust(width[, fillchar]) – 右对齐,左填充

代码print( "我".rjust(4,"=") )结果

===我

↑TOP↑str.center(width[, fillchar]) – 居中,两边填充

代码print( "我是分割线".center(30, "=") )结果============我是分割线=============

↑TOP↑str.lstrip([chars]) – 去除左空白或自定字符

代码'   spacious   '.lstrip()结果'spacious   '代码'www.example.com'.lstrip('cmowz.')结果'example.com'

↑TOP↑str.rstrip([chars]) – 去除右空白或自定字符

代码'   spacious   '.rstrip()结果'   spacious'代码'mississippi'.rstrip('ipz')结果'mississ'

↑TOP↑str.strip([chars]) – 去除两边空白或自定字符

代码'   spacious   '.strip()结果'spacious'代码'www.example.com'.strip('cmowz.')结果'example'

↑TOP↑str.swapcase() – 大小写互转

代码print( "Abc".swapcase() )结果aBC

↑TOP↑str.zfill(width) – 左侧填充0到指定宽,一般用来修饰数字

代码print( "15".zfill(8) )结果00000015代码print( "-15".zfill(8) )结果-0000015

↑TOP↑str.count(sub[, start[, end]]) – 计算[start, end)间,sub出现次数

代码print( "abababab" .count("abab" )结果2

注:非重叠计数,因此结果是2而不是3

1.4 datetime.datetime

获取当前时间,并通过字符串输出。

格式为:%Y-%m-%d %H:%M:%S'

datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' )

获取当前时间,但只保留日期

datetime.datetime.now().date()

将字符串转换为datetime类型

输入字符串格式为:'%Y-%m-%d'

datetime.datetime.strptime(time,'%Y-%m-%d')

 

print 'start at:',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f' )
print 'start at:',time.strftime('%Y-%m-%d %H:%M:%S.%f', time.localtime(time.time()))

附录:

格式化符号汇总
%a 星期几的简写 Weekday name, abbr.
%A 星期几的全称 Weekday name, full
%b 月分的简写 Month name, abbr.
%B 月份的全称 Month name, full
%c 标准的日期的时间串 Complete date and time representation
%d 十进制表示的每月的第几天 Day of the month
%H 24小时制的小时 Hour (24-hour clock)
%I 12小时制的小时 Hour (12-hour clock)
%j 十进制表示的每年的第几天 Day of the year
%m 十进制表示的月份 Month number
%M 十时制表示的分钟数 Minute number
%S 十进制的秒数 Second number
%U 第年的第几周,把星期日做为第一天(值从0到53)Week number (Sunday first weekday)
%w 十进制表示的星期几(值从0到6,星期天为0)weekday number
%W 每年的第几周,把星期一做为第一天(值从0到53) Week number (Monday first weekday)
%x 标准的日期串 Complete date representation (e.g. 13/01/08)
%X 标准的时间串 Complete time representation (e.g. 17:02:10)
%y 不带世纪的十进制年份(值从0到99)Year number within century
%Y 带世纪部分的十制年份 Year number
%z,%Z 时区名称,如果不能得到时区名称则返回空字符。Name of time zone
%% 百分号




原创粉丝点击