Python中read和write⽤法1、读操作
读操作有read、readline和readlines函数
看⽰例:
[python] view plain copy
1. f = open('1.txt','r')
2. data = f.read() #读出所有的内容
3. print data
4. f.close()
结果:
[python] view plain copy
1. >>>
2. I'm OK!
3. I'm fine!
4. Hello world!
[python] view plain copy
1. f = open('1.txt','r')
2. data = f.readline() #只读⼀⾏
3. print data
4. f.close()
结果:
[python] view plain copy
1. >>>
writelines在python中的用法2. I'm OK!
[python] view plain copy
1. f = open('1.txt','r')
2. data = f.readlines() #⽣成的是列表
3. print data
4. f.close()
结果:
[java] view plain copy
1. >>>
2. ["I'm OK!\n", "I'm fine!\n", 'Hello world!\n']
2、写操作
写操作有write、writelines,切记没有writeline
看⽰例:
[python] view plain copy
1. data = ["abc","def"]
2. f = open('2.txt','w')
3. f.write(data)
4. f.close()
结果:
[python] view plain copy
1. >>>
2.
3. Traceback (most recent call last):
4.  File "D:\Program Files\python\chengxu\temp.py", line 9, in <module>
5.    f.write(data)
6. TypeError: expected a character buffer object
当写的数据为list数组时,⽤write函数会出错,换⽤writelines函数