Python学习笔记——文件对象和操作(2)

三 文件内建属性

简单介绍一下:

file.closed True表示文件已经关闭,否则为False  例如 if file.closed= =True:

file.encoding   文件所用的编码

file.mode 文件打开时的访问模式

file.name  文件名

等等

 

四 标准文件

执行程序可以访问三个标准文件,标准输入,标准输出,标准错误,分别为stdinstdout stderr

Python中可以通过sys模块来访问这些文件的句柄,导入sys模块,就可以使用sys.stdin

Sys.stdout和sys.stderr

 

五 文件系统

对文件系统的访问大多通过Python的os模块实现。该模块是Python访问操作系统功能的主要接口。

另外一个模块os.path可以完成一些针对路径名的操作,它提供的函数可以完成管理和操作文件路径名种的各个部分,获取文件或者子目录信息,文件路径查询等。

两个模块中的函数就不一一介绍了。看几个例子:

>>> import os

>>> os.getcwd()

'C:\\Python26'

>>>os.chdir('C:\Python26\code')

>>> os.getcwd()

'C:\\Python26\\code'

首先导入os模块,然后是用getcwd()获取当前工作目录,然后用chdir()改变当前工作目录

>>>os.path.isdir('\code')

False

>>>os.path.isdir('C:\Python26')

True

这是判断一个目录是否存在。

 

>>> os.getcwd()

'C:\\Python26\\code'

>>>os.mkdir('example')

>>>os.chdir('example')

>>> cwd =os.getcwd()

>>> cwd

'C:\\Python26\\code\\example'

>>>os.listdir(cwd)

[]

>>>os.listdir('C:\Python26')

['code', 'DLLs', 'Doc', 'include','Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe','pythonw.exe', 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']

>>>

mkdir()类似于Linux里的mkdir,是在当前目录下新建一个空目录,进入这个目录,用listdir()可以查看是否为空。listdir(目录)是列出该目录下的文件或者子目录,类似于Linux里的ls命令。

 

>>> cwd =os.getcwd()

>>> cwd

'C:\\Python26\\code\\example'

>>>os.listdir(cwd)

[]

>>> fobj=  open('test','w')

>>>fobj.write('foo\n')

>>>fobj.write('bar\n')

>>> fobj.close()

>>>os.listdir(cwd)

['test']

>>>os.rename('test','filetest.txt')

>>>os.listdir(cwd)

['filetest.txt']

>>>

我们在刚才新建的目录example中写一个名为test的文件,然后用rename()来改名字。

>>> path =os.path.join(cwd,os.listdir(cwd)[0])

>>> path

'C:\\Python26\\code\\example\\filetest.txt'

>>>os.path.isfile(path)

True

>>>os.path.isdir(path)

False

>>>os.path.split(path)

('C:\\Python26\\code\\example','filetest.txt')

>>>os.path.splitext(os.path.basename(path))

('filetest', '.txt')

>>>

上面是些path里面的一些函数。

 

>>> fobj =open(path)

>>> for eachLine infobj:

print eachLine,

 

 

foo

bar

>>>os.remove(path)

>>> fobj.close()

>>>os.remove(path)

>>>os.listdir(cwd)

[]

>>>os.chdir(os.pardir)

>>> os.getcwd()

'C:\\Python26\\code'

>>>os.rmdir('example')

上面是显示内容,然后是删除文件,删除目录。

 

Os模块很强大的,这里只是简单的介绍了几个应用,它的更多应用以后还要继续学习。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值