Python基础-IO与文本处理

来源:互联网 发布:手机淘宝修改差评 编辑:程序博客网 时间:2024/05/19 08:22

标准IO设备的操作

print语句

print语句可以将内容输出到标准输出上,如print 'hello';除此之外,print还可以将内容输出到文件对象里

123
>>> import sys>>> print >> sys.stderr,'hello'  #将内容输出到标准错误中hello

print函数包含在__future__模块中:

1234567891011
>>> from __future__ import print_function     #从__future__函数中导入print函数>>> type(print)<type 'builtin_function_or_method'>    #此时,print不再是一个语句,而是一个函数>>> >>> print("hello","world")hello world>>> print("hello","world",sep='\n')    #print函数具有比print语句更强大的功能,sep:分隔符helloworld>>> print("hello","world",sep='*')hello*world

raw_input函数

一个内置函数,从标准输入读取内容

12345678
>>> s = raw_input()hello>>> s'hello'>>> s = raw_input("please input a word >> ")please input a word >> key>>> s'key'

open函数与file对象

open()是一个内置函数。open(name[,mode[,buffering]]),其实是对file的一个封装,返回一个file对象

具体参数

r 以读的方式打开,定位到文件开头,默认的mode
r+ 以读写的方式打开,定位文件开头,可以写入内容到文件
w 以写的方式打开,打开文件的时候会清空文件的内容,并且不能读
w+ 以读写的方式打开,定位到文件头,并且打开文件的时候也会清空文件的内容
a 以写的方式打开,定位到文件的末尾,是一个追加的操作,但并不允许读
a+ 以读写的方式打开,定位到文件的末尾,追加的方式。
在使用以上mode打开文件的时候,如果增加了b 模式,表示以二进制方式打开
示例:

123456789101112131415161718
>>> f = open('/mnt/file','r')   #以只读方式打开/mnt/file文件>>> f.read()   #文件为空,所以读出来的为空''>>> f.close()   #打开的文件最终要关闭。每打开一个文件会消耗一个文件描述符,如果打开太多会消耗掉所有的文件描述符就不能再打开文件了,关闭之后可以释放文件描述符,所以要记得关闭>>> f = open('/mnt/file','w')>>> f.read()Traceback (most recent call last):File "<stdin>", line 1, in <module>IOError: File not open for reading    #以只写方式打开则不能读>>> f.write('hello')>>> f.close()>>> f = open('/mnt/file')   #默认的为只读方式打开>>> f.read()'hello'>>> f.read()''>>> f.close()

file对象的一些操作

read()

read()表示读取文件所有内容到内存里,可以带一个可选参数表示读取多少字节。当打开较大的文件时慎用

12345678910
>>> f = open('/mnt/file') #只读形式打开>>> f.read()'12345678910\n12345678910\n12345678910\n'>>> f.read(4)  #意图读四个字节,但文件指针已经到了文件末尾,读不出东西了''>>> f = open('/mnt/file')>>> f.read(4)  #一次读取四个字节'1234'>>> f.read(4)'5678'

readline()

读取一行内容

123456789
>>> f = open('/mnt/file')>>> f.readline()'12345678910\n'>>> f.readline()'dshdiaufhies\n'>>> f.readline()'hello\n'>>> f.readline()''

readlines()

将所有行内容读到一个列表里,会将换行符读取进来

1234
>>> f = open('/mnt/file')>>> f.readlines()['12345678910\n', 'dshdiaufhies\n', 'hello\n']>>> f.close()

write()

将内容写入到文件

1234567
>>> f = open('/mnt/file','w')>>> f.write('hello world hello tonglele')>>> f.close()>>> f = open('/mnt/file')>>> f.read()'hello world hello tonglele'>>> f.close()

writelines()

将一个序列写入到文件中,但不会加换行符

1234567
>>> f = open('/mnt/file','w')>>> f.writelines(['hello world','hello tonglele'])>>> f.close()>>> f = open('/mnt/file')>>> f.read()'hello worldhello tonglele'>>> f.close()

truncate()

f.truncate()清空文件,但是!!如果以a的方式打开,则不会清空,因为a的方式是定位到文件末尾,
该函数是从文件指针当前位置开始清空的

12345678910111213141516171819202122
root@tonglele /code/Python/IO/test # cat /mnt/filehello worldhello tongleleroot@tonglele /code/Python/IO/test # pythonPython 2.7.5 (default, Feb 11 2014, 07:46:25) [GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> f = open('/mnt/file','a')>>> f.truncate()>>> f.close()>>> root@tonglele /code/Python/IO/test # cat /mnt/filehello worldhello tongleleroot@tonglele /code/Python/IO/test # python       Python 2.7.5 (default, Feb 11 2014, 07:46:25) [GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> f = open('/mnt/file','w')>>> f.truncate()>>> f.close()>>> root@tonglele /code/Python/IO/test # cat /mnt/fileroot@tonglele /code/Python/IO/test #

flush()

flush()函数,将缓冲区的内容写入到硬盘中,close()函数在关闭文件之前会执行此操作。

tell()

返回当前文件指针的偏移量

12345678
>>> f = open('/mnt/file','r')>>> f.tell()0>>> f.read()'dhsiadh\nhdsaih\nhsaifuf\nfsoh\nasi\n'>>> f.tell()32>>> f.close()

seek()

seek,seek(offset[,whence])offset表示移动多少字节,whence为1的时候表示相对于当前位置移动的;
当2的时候从文件的末尾往后移动,但不一定所有的平台都支持;默认为0表示从文件开头往后移动

1234567891011121314
>>> f = open('/mnt/file','r')>>> f.tell()0>>> f.read()'dhsiadh\nhdsaih\nhsaifuf\nfsoh\nasi\n'>>> f.read()''>>> f.tell()32>>> f.seek(10)>>> f.tell()10>>> f.read()'saih\nhsaifuf\nfsoh\nasi\n'

close()

close()函数,关闭当前打开的文件

fileno()

fileno()函数,返回当前的文件描述符,一个数字

1234
>>> f = open('/mnt/file','r')>>> f.fileno()4>>> f.close()

isatty()

isatty()函数,当前打开的文件是否是一个终端设备
如果该文件被连接(与终端设备相关联)到一个tty(类似终端)设备,此方法返回True,否则False

1234
>>> f = open('/mnt/file','r')>>> f.isatty()False>>> f.close()

closed

closed属性,查看当前文件对象是否被关闭

123456
>>> f = open('/mnt/file','r')>>> f.closedFalse>>> f.close()>>> f.closedTrue

next()

next()方法,一行一行的读取,(file对象是一个迭代器,可以放在for循环里)

12345678910111213141516171819202122232425262728
>>> f = open('/mnt/file','r')>>> f.next()'dhsiadh\n'>>> f.next()'hdsaih\n'>>> f.next()'hsaifuf\n'>>> f.next()'fsoh\n'>>> f.next()'asi\n'>>> f.next()Traceback (most recent call last):  File "<stdin>", line 1, in <module>  StopIteration  >>> f.close()  >>> for line in open('/mnt/file'):  ...     print line  ...   dhsiadh    hdsaih    hsaifuf    fsoh    asi

with语法

一般情况下打开一个文件,经过操作之后,都要显示的执行close()将其关闭
with用于需要打开,关闭成对的操作,可以自动关闭打开的对象

1234
 with expression as obj:    expression将打开的对象赋给obj  obj的作用域只在with语句快中
12345678910111213
>>> with open('/mnt/file') as f:...     for line in f:...             print line... dhsiadhhdsaihhsaifuffsohasi

文本处理

字符串处理

split函数

split函数,默认以空格分隔,可以传指定分隔符,传指定分隔片个数

12345678910111213
>>> str = 'tonglele tongyijia'>>> str.split()['tonglele', 'tongyijia']>>> str = 'hello!world'>>> str.split('!')  #指定分隔符['hello', 'world']>>> str = 'hihialoloapjpjommmolll'>>> str.split('o',1) #指定分隔符及分隔片个数['hihial', 'loapjpjommmolll']>>> str.split('o',2)['hihial', 'l', 'apjpjommmolll']>>> str.split('o',3)['hihial', 'l', 'apjpj', 'mmmolll']

join函数

join函数,字符串的连接,用于连接一个迭代器,返回一个字符串

123456
>>> it = ['hel','lo']>>> "".join(it)'hello'>>> it = ['h','e','l','l','o']>>> "-".join(it)'h-e-l-l-o'

+也可以连接字符串,由于字符串是不可变的,所以在使用加号连接两个字符串的时候需要创建新的内存用来存储数据

字符串格式化

Python中字符串格式化主要有两种方式
占位符,%s字符串,%d整数,%f浮点数

1234
>>> "hello %s" % "tonglele"'hello tonglele'>>> "hello %s hello %d hello %f" % ("tonglele",18,7.7)'hello tonglele hello 18 hello 7.700000'

字符串查找 find()函数

find()函数,返回字符串在原字符串中第一次出现的位置,若没找到则返回-1

1234567891011
>>> str = "hello tonglele">>> str.find('o')4>>> str.find('hell')0>>> str.find('lele')10>>> str.find('tongyijia')-1>>> str.find('e',10,14) #还可以接受两个可选参数,start,end用于标示查找时的起始位置和结束位置11

字符串替换

replace函数

replace函数,用于替换

123
>>> str = "hello tonglele">>> str.replace("lele","yijia")'hello tongyijia'

strip函数

strip函数,用来替换字符串首尾的空白(空格、制表符\r、\n、\t)

123456789101112
>>> str = "hello tonglele     ">>> str.strip()'hello tonglele'>>> str = "hello tonglele       ">>> str.strip()'hello tonglele'>>> str = "hello tonglele       ">>> str = "hello tonglele\n">>> str'hello tonglele\n'>>> str.strip()'hello tonglele'

rstrip 移除右边的空白,lstrip移除左边的空白

感谢阅读,欢迎指正。


0 0
原创粉丝点击