Python的文件

来源:互联网 发布:桃源网络硬盘破解 编辑:程序博客网 时间:2024/06/05 05:01

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_SET0>>> os.SEEK_CUR1>>> os.SEEK_END2>>> 

文件方法

打开

  • 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 sysdef 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 Peterhello, arg: Peter

说明:当我们在命令行运行当前.py模块文件时,Python解释器把一个特殊变量__name__置为__main__
而如果在其他地方导入该.py模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是执行测试。

文件系统

  • os模块
    对文件系统访问的主要接口。
    具体可参考os模块

  • os.path模块
    用以完成一些针对路径名的操作。
    具体可参考os.path模块

这两个模块提供了与平台和操作系统无关的统一的文件系统访问方法。


0 0
原创粉丝点击