python核心编程第九章_文件系统的一个程序

来源:互联网 发布:什么叫域名 编辑:程序博客网 时间:2024/06/06 17:45

今天看到文件系统,书上有一个案例,主要是针对模块os和os.path的一些方法,摘抄如下:

#-*-coding:utf-8-*-import osfor tmpdir in (r'E:\python\core_program\practice\core_code\chap_9',r'E:\python'):    if os.path.isdir(tmpdir):        //判断制定路径是否存在且为一个目录        breakelse:    print 'no temp directory available'    tmpdir = ''if tmpdir:    os.chdir(tmpdir)                //改变当前工作目录至tmpdir目录中
    cwd = os.getcwd()    //获取当前文件目录路径    print '***current temporar directory***'    print cwd    print '***creating example directory...'    os.mkdir('example')            //创建一个新的工作目录    os.chdir('example')            //同样的,改变当前目前至example文件夹中    cwd = os.getcwd()                      print '***new workding directory:'    print cwd    print '***original directory listing:'    print os.listdir(cwd)          //列出指定目录的文件    print "***creating test file ..."    fobj = open('test','w')    fobj.write('foo\n')    fobj.write('bar\n')    fobj.close()    print "***updated directory listing:"    print os.listdir(cwd)    print "*** renaming 'test' to 'filetest.txt'"    os.rename('test','filetest.txt')    print "***updated directory listing:"    print os.listdir(cwd)    path = os.path.join(cwd,os.listdir (cwd)[0]) // 我将cwd[0]打印出来,是盘符E,不太懂!    print '***full file pathname'    print path    print "***(pathname,basename) =="    print os.path.split(path) //把文件目录和文件分开组成二元元组    print "***(filename,extension) =="    print os.path.splitext(os.path.basename(path)) //将整个文件名和目录联合起来,而将后缀名分开    print "***displaying file contents:"    fobj = open(path)    for eachLine in fobj:        print eachLine,    fobj.close()    print "*** deleting test file "    os.remove(path)    print "***updated directory listing:"    print os.listdir(cwd)    os.chdir(os.pardir)    print "*** deleting test directory"    os.rmdir('example')    print "***DONE"

os.path.join(path1[, path2[, ...]])将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。>>> os.path.join('c:\\', 'csv', 'test.csv')'c:\\csv\\test.csv'>>> os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv')'c:\\csv\\test.csv'>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')'/home/aa/bb/c'



原创粉丝点击