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

Python的文件

2015-07-21 17:15 218 查看

Python的文件

文件对象

参考官方文档_文件对象

一些跨平台的os模块的属性:

os模块属性说明
os.curdir
.
‘(Windows and POSIX)
os.pardir
..
‘(Windows and POSIX),父目录
os.devnull
/dev/null
‘(POSIX)、’
nul
‘(Windows),null device的路径
os.sep
/
‘(POSIX)、’
\\
‘(Windows),路径的分割
os.pathsep
:
‘(POSIX)、’
;
‘(Windows),搜索路径的分割(as in PATH
os.linesep
\n
‘(POSIX)、’
\r\n
‘(Windows),注意Do not use
os.linesep
as a line terminator when writing files opened in text mode (the default); use a single ‘
\n
’ instead, on all platforms.
(注:\r = RETURN, \n = NEWLINE)

>>> import os
>>> os.name
'nt'
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.devnull
'nul'
>>> os.sep
'\\'
>>> os.pathsep
';'
>>> os.linesep
'\r\n'
>>> os.SEEK_SET
0
>>> os.SEEK_CUR
1
>>> os.SEEK_END
2
>>>


文件方法

打开

open()



read()

readline()

readlines()



write()

writelines()

truncate()

flush()

其它

tell()

seek()

关闭

close()

文件属性

name

mode

closed

命令行参数

sys模块通过
sys.argv
属性提供了对命令行参数的访问。

sys.argv 命令行参数列表

len(sys.argv) 命令行参数的个数(相同于C语言中的argc)

例子:

# coding=utf-8
__author__ = 'Z'

import sys

def sayhello():
v = sys.argv
if len(v) == 1:
print 'hello world'
elif len(v) == 2:
print 'hello, arg: %s' % v[1]
else:
print 'too many args'

if __name__ == '__main__':
sayhello()

运行结果:
>python test.py Peter
hello, arg: Peter


说明:当我们在命令行运行当前.py模块文件时,Python解释器把一个特殊变量
__name__
置为
__main__


而如果在其他地方导入该.py模块时,
if
判断将失败,因此,这种
if
测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是执行测试。

文件系统

os模块

对文件系统访问的主要接口。

具体可参考os模块

os.path模块

用以完成一些针对路径名的操作。

具体可参考os.path模块

这两个模块提供了与平台和操作系统无关的统一的文件系统访问方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: