天天看点

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.write("This is the {0}\n".format("start"))

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

3.file常用方法

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

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

print(file1.readlines())

readline():每次读取一行

print(file1.readline())

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

print(file1.next())

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

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

list1 = ["a","b","c"]

file1 = codecs.open("example.txt","a")

file1.writelines(list1)

注:数字序列则报错,需强制转换类型,如str(i)

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

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

file1.seek(0)

file1.write("cc")

print(file1.tell())

其他的方法:

f.name    查看文件的名字

print f.closed     布尔值,判断文件是否关闭

print f.encoding()   查看文件的编码

f.mode    查看文件的打开模式

flush():刷新文件缓存

4.file的with用法

with:将1.txt赋值给f,再去操作f,这样写格式灵活,不需要考虑文件关闭的情况

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

   print(file1.read())

   file1.close()

closed:判断是否关闭

   print(file1.closed)

print(file1.closed)

enumerate:打印行号

   for line,value in enumerate(file1):

       print(line,value)

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

import linecache

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

print(count)

本文转自 huangzp168 51CTO博客,原文链接:http://blog.51cto.com/huangzp/1976937,如需转载请自行联系原作者