Python中read和write用法

1、读操作

读操作有read、readline和readlines函数

看示例:

f = open('1.txt','r')   
data = f.read() #读出所有的内容
print data  
f.close()
结果:

>>> 
I'm OK!
I'm fine!
Hello world!

f = open('1.txt','r')   
data = f.readline() #只读一行
print data  
f.close()
结果:

>>> 
I'm OK!

f = open('1.txt','r')   
data = f.readlines() #生成的是列表
print data  
f.close() 
结果:

>>> 
["I'm OK!\n", "I'm fine!\n", 'Hello world!\n']

2、写操作

写操作有write、writelines,切记没有writeline

看示例:

data = ["abc","def"]
f = open('2.txt','w')
f.write(data)
f.close()
结果:

>>> 

Traceback (most recent call last):
  File "D:\Program Files\python\chengxu\temp.py", line 9, in 
    f.write(data)
TypeError: expected a character buffer object
当写的数据为list数组时,用write函数会出错,换用writelines函数


你可能感兴趣的:(Python,Python,read,write)