Python的文件

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模块

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值