9.4 文件内建属性
file.closed 表示文件已经被关闭,否则为false。
>>> file1 = open("C:\\Documents and Settings\\10170660\\Desktop\\1.txt", mode = "U")
>>> file1.closed
False
>>>
file.encoding文件所使用的编码。
>>> print file1.encoding
None
>>>
file.mode Access文件打开时使用的访问模式。
>>> file1.mode
'U'
file.name 文件名
>>> file1.name
'C:\\Documents and Settings\\10170660\\Desktop\\1.txt'
>>>
9.5 标准文件
一般来说,只要你程序一执行,你就可以访问3个标准文件。他们分别是标准输入(一般是键盘),标准输出(到显示器的缓冲输出)和标准错误(到屏幕的非缓冲输出),这些文件沿用的是C语言的命名,分别是stdin,stdout和stderr。
Python中可以通过sys模块来访问这些文件的句柄。导入sys模块后,就可以使用sys.stdin,sys.stdout和sys.stderr访问。print语句通常输出到sys.stdout;而内建raw_input()则通常从sys.stdin接收输入。
9.6 命令行参数
sys模块通过sys.argv属性提供了对命令行参数的访问。命令行参数是调用某个程序时除程序名以外的其他参数。大多IDE环境都提供一个用来输出“命令行参数”的窗口;这些参数最后会像命令行上执行那样被传递给程序。
sys.argv是命令行参数的列表。
len(sys.argv)是命令行参数的个数(也就是argc)。
>>> import sys
>>> print 'you entered', len(sys.argv), 'arguments...'
you entered 1 arguments...
>>> print 'thery were: ', str(sys.argv)
thery were: ['']
>>>
9.7 文件系统
对文件系统的访问大多通过Python的os模块实现。
另一个模块os.path可以完成一些针对路径名的操作。它提供的函数可以完成管理和操作文件路径名中的各个部分,获取文件或子目录信息,文件路径查询等操作。
>>> os.mkdir("example")
>>> print `os.getcwd()`
'C:\\Python27\\Lib\\site-packages\\pythonwin'
>>> os.chdir('example')
>>> print `os.getcwd()`
'C:\\Python27\\Lib\\site-packages\\pythonwin\\example'
>>> os.listdir(os.getcwd())
[]
>>> os.chdir('C:\\Python27\\Lib\\site-packages\\pythonwin')
>>> os.listdir(os.getcwd())
['dde.pyd', 'example', 'license.txt', 'mfc90.dll', 'mfc90u.dll', 'mfcm90.dll', 'mfcm90u.dll', 'Microsoft.VC90.MFC.manifest', 'Pythonwin.exe', 'pywin', 'scintilla.dll', 'win32ui.pyd', 'win32uiole.pyd']
>>> os.rename('example', 'test')
>>> os.listdir(os.getcwd())
['dde.pyd', 'license.txt', 'mfc90.dll', 'mfc90u.dll', 'mfcm90.dll', 'mfcm90u.dll', 'Microsoft.VC90.MFC.manifest', 'Pythonwin.exe', 'pywin', 'scintilla.dll', 'test', 'win32ui.pyd', 'win32uiole.pyd']
>>> import os.path
>>> os.path.isdir('test')
True
>>> os.path.isfile('license.txt')
True
>>> os.path.isdir("ad")
False
>>>