码迷,mamicode.com
首页 > 编程语言 > 详细

零基础学python-9.2 文件

时间:2015-08-29 23:17:35      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:python

1.文件的操作:

操作

解释

output=open(r‘c:\123.txt‘,‘w‘)

创建输出文件,w写入

input=open(‘data‘,‘r‘)

创建输出文件,r读取

input=open(‘data‘)

创建输出文件,r默认

s=input.read()

整个文件读取单一字符串

s=input.read(N)

读取之后的n个字节到字符串

s=input.readline()

读取下一行到一个字符串

alist=input.readlines()

读取整个文件到字符串列表

output.write(s)

写入字节字符串到文件

output.writelines(list)

把列表内所有字符串写入文件

output.close()

手动关闭

output.flust()

清空缓存

anyFile.seek(N)

查询

for line in open(‘data‘):use line

逐行读取

open(‘f.txt‘,encodeing=‘latin-1‘)

设置unicode

open(‘f.bin‘,‘rb‘)

 

 

2.基本操作实例

>>> myfile=open('123.txt','w')
>>> myfile.write
<built-in method write of _io.TextIOWrapper object at 0x012D8D30>
>>> myfile.write('hello world \n')
13
>>> myfile.write('hello world 2 \n')
15
>>> myfile.close ()
>>> myfile=open('123.txt')
>>> myfile.readline
<built-in method readline of _io.TextIOWrapper object at 0x0170B5B0>
>>> myfile.readline ()
'hello world \n'
>>> myfile.readline ()
'hello world 2 \n'
>>> myfile.readline ()
''
>>> 


上面是读取、写入文件

 

3.只有字符串才能够写入文件

>>> myfile=open('123.txt','w')
>>> l=(1,2,3)
>>> myfile.write(l)
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    myfile.write(l)
TypeError: must be str, not tuple
>>> 
>>> t=[1,2,3]
>>> myfile.write(t)
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    myfile.write(t)
TypeError: must be str, not list
>>> 



 

 

就说到这里,谢谢大家

------------------------------------------------------------------

点击跳转零基础学python-目录

版权声明:本文为博主原创文章,未经博主允许不得转载。

零基础学python-9.2 文件

标签:python

原文地址:http://blog.csdn.net/raylee2007/article/details/48093153

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!