python核心程式設計學習(三)

2021-06-04 16:04:13 字數 2483 閱讀 5747

核心程式設計中的檔案操作的例子:

'''

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\n')

fobj.write('bar\n')

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:

foobar

*** deleting test file

*** updated dir listing:

*** deleting test dir

*** done

Python 核心程式設計 筆記三

1 字典是python中唯一的對映型別。映像型別中的資料是無序排列的。字典是作為可變的哈係表實現的。2 字典操作 建立字典 訪問字典 dict for key in dict print r r n key,dict key age 22 name joe male dict dictcp dict...

python核心程式設計學習(一)

以下是核心程式設計中乙個stack的例子 created on 2012 3 6 author administrator usr bin env python stack def pu def popit if len stack 0 print has empty else print remo...

python核心程式設計學習(四)

乙個計算簡單加減法的例子 created on 2012 3 7 author administrator usr bin env python from operator import add,sub from random import randint,choice ops maxtries 2...