您的位置:首页 > 编程语言 > Python开发

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

2012-12-09 14:29 761 查看
三 文件内建属性
简单介绍一下:
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模块很强大的,这里只是简单的介绍了几个应用,它的更多应用以后还要继续学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: