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

python文件操作

时间:2017-10-28 11:23:09      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:python

1.file读文件


读取文件的步骤:

1.打开文件

2.文件操作(读或者写、替换replace)

3.关闭文件


例子:

import codecs   

file1 = codecs.open("1.txt")

print(file1.read())

file1.close()


说明:codecs 导入模块,解决文件乱码文件的类


2.file写文


写文件重要参数:

读取:r

写:w

二进制:b

追加:a


例子:

import codecs

file1 = codecs.open("1.txt","ab")

file1.write("This is the start\n")

file1.write("This is the end \n")

file1.close()


或者

import codecs

file1 = codecs.open("1.txt","ab")

file1.write("This is the {0}\n".format("start"))

file1.write("This is the %s\n" %"end")

file1.close()


3.file常用方法

readlines():读取所有文件,把文件每行的内容,作为字符串的元素,放在list中

例子:

import codecs

file1 = codecs.open("1.txt","rb")

print(file1.readlines())

file1.close()


readline():每次读取一行

例子:

import codecs

file1 = codecs.open("1.txt","rb")

print(file1.readline())

print(file1.readline())

file1.close()


next():读取文件下一行内容作为一个字符串

例子:

import codecs

file1 = codecs.open("1.txt","rb")

print(file1.readline())

print(file1.next())

file1.close()


write():必须写入一个字符串,和read()对应

例子:

import codecs

file1 = codecs.open("1.txt","wb")

file1.write("aaaa")

file1.close()


writelines():必须写入一个列表,和readines()对应

例子:

import codecs

file1 = codecs.open("1.txt","wb")

file1.writelines(["aaaa","bbbb"])

file1.close()


writelines():必须写入一个列表,和readines()对应

例子:

import codecs

file1 = codecs.open("1.txt","wb")

file1.writelines(["aaaa","bbbb"])

file1.close()


seek():定位光标移到某位置,例子中从光标位置开始写会覆盖原来全部内容

例子:

import codecs

file1 = codecs.open("1.txt","wb")

file1.seek(0)

file1.write("cc")

print(file1.tell())

file1.close()


flush():刷新文件缓存


4.file的with用法

with:将1.txt赋值给f,再去操作f,这样写格式灵活

例子:

import codecs

with codecs.open("1.txt","rb") as file1:

   print(file1.read())

   file1.close()


closed:判断是否关闭

例子:

import codecs

with codecs.open("1.txt","rb") as file1:

   print(file1.read())

   print(file1.closed)

   file1.close()

print(file1.closed)



enumerate:打印行号

例子:

import codecs

with codecs.open("1.txt","rb") as file1:

   for line,value in enumerate(file1):

       print(line,value)


linecache:从名为filename的文件中得到全部内容,输出为列表格式

例子:

import linecache

count = linecache.getline("1.txt",3)

print(count)


python文件操作

标签:python

原文地址:http://huangzp.blog.51cto.com/12434999/1976937

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