python 핵심 프로 그래 밍 학습 (3)

2407 단어 python
핵심 프로 그래 밍 의 파일 작업 예:
'''
Created on 2012-3-7

@author: Administrator
'''
#!/usr/bin/env python
import os

for tmpdir in('C:\\','r'):
    if os.path.isdir(tmpdir):
        print tmpdir
        break
    else:
        print 'no temp'
        tmpdir=''
        
if tmpdir:
    os.chdir(tmpdir)
    cwd = os.getcwd()
    print '**** current temp dir'
    print cwd
    
print '*** creating example dir...'
os.mkdir('example')
os.chdir('example')
cwd = os.getcwd()
print '*** new working dir'
print cwd
print '*** original dir listing:'
print os.listdir(cwd)

print "*** creating  test file..."
fobj = open('test','w')
fobj.write('foo
') fobj.write('bar
') fobj.close() print '*** updated dir listing:' print os.listdir(cwd) print "*** renaming 'test' to 'filetest.txt'" os.rename('test', 'filetest.txt') print '*** updated dir listing:' print os.listdir(cwd) path = os.path.join(cwd,os.listdir(cwd)[0]) 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 dir listing:' print os.listdir(cwd) os.chdir(os.pardir) print '*** deleting test dir' os.rmdir('example') print '*** done'
pydev debugger: starting
C:\
**** current temp dir
C:\
*** creating example dir...
*** new working dir
C:\example
*** original dir listing:
[]
*** creating  test file...
*** updated dir listing:
['test']
*** renaming 'test' to 'filetest.txt'
*** updated dir listing:
['filetest.txt']
***full file pathname
C:\example\filetest.txt
***(pathname,basename)==
('C:\\example', 'filetest.txt')
***(filename,extension)==
('filetest', '.txt')
*** displaying file contents:
foo

bar

*** deleting test file
*** updated dir listing:
[]
*** deleting test dir
*** done

좋은 웹페이지 즐겨찾기