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

python文件操作

时间:2017-09-18 00:29:22      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:flat   cat   字符串   ted   文件的操作   better   使用   字符   xpl   

Python实现文件的操作:

读写一个文件之前需要打开它:

fileobj = open(filename, mode)

open()调用参数的解释:

* fileobj是open()返回的文件对象; 

* filename是该文件的字符串名;

* mode是指明文件类型和操作的字符串

mode :

* r 只读模式(默认)

* w 只写模式(不可读,不存在则新创建;存在则重写新内容;)

* a 追加模式(可读,不存在则新创建;存在则只追加内容;)

 

"+" 表示同时读写某个文件:

* r+ 可读写文件(可读;可写;可追加)

* w+ 写读

* a+ 同a

 

* b代表二进制文件  

eg:写文件

conten = ‘‘‘Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.‘‘‘

fout = open("file.txt", "w")
fout.write(conten)
fout.close()

 

如果源字符串比较大,可以将数据进行分块,直到所有字符被写入:

fout = open("file.txt", "w")
size = len(conten)
offset = 0
chunk = 100
while True:
if offset > size:
break
fout.write(conten[offset:offset+chunk])
offset += chunk
fout.close()

***使用read()、readline()、readlines()读文件本文件:

不带参数的read()函数一次读入文件的所有内容,在读入文件时注意,2G的文件会用到相同大小的内存

fin = open("file.txt", "r")
ct = fin.read()
fin.close()
print(ct)

可以设置最大的读入字符数限制read()函数一次返回的大小。

ct = ""
chunk = 100
fin = open("file.txt", "r")
while True:
fragment = fin.read(chunk)
if not fragment:
break
ct += fragment
fin.close()
print(ct)

 

readline()每次读入文件的一行,通过追加每一行拼接成原来的字符串:

ct = ""
fin = open("file.txt", "r")
while True:
line = fin.readline()
if not line:
break
ct += line
fin.close()
print(ct)
fin = open("file.txt", "r")
while True:
line = fin.readline()
if not line:
break
print(line,end="")
fin.close()

当文件读取结束后,readline()、read()同样会返回空字符串,即被判为False.

 

函数readlines()调用时每次读取一行,并返回单行字符串的列表:

fin = open("file.txt", "r")
lines = fin.readlines()
fin.close()
for line in lines:
print(line, end="")

 

使用with自动关闭文件:

with open("file.txt", "r") as fin:
while True:
line = fin.readline()
if not line:
break
print(line, end="")

*** 使用seek()改变位置 

函数tell()返回距离文件开始处的字节偏移量,函数seek()允许跳转到文件其它字节偏移量的位置,即可以不用从头读取文件的每一个字节,直接跳到指定的位置

fin = open("file.txt", "r")
fin.tell()
print(fin.read())
fin.seek(10)
print(fin.read())

 

python文件操作

标签:flat   cat   字符串   ted   文件的操作   better   使用   字符   xpl   

原文地址:http://www.cnblogs.com/helloworld899/p/7538401.html

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