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()对应
writelines():必须写入一个字符串列表,和readines()对应
例子:
import codecs
list1 = ["a","b","c"]
file1 = codecs.open("example.txt","a")
file1.writelines(list1)
注:数字序列则报错,需强制转换类型,如str(i)
seek():定位光标移到某位置,例子中从光标位置开始写会覆盖原来全部内容
例子:
import codecs
file1 = codecs.open("1.txt","wb")
file1.seek(0)
file1.write("cc")
print(file1.tell())
file1.close()
其他的方法:
f.name 查看文件的名字
print f.closed 布尔值,判断文件是否关闭
print f.encoding() 查看文件的编码
f.mode 查看文件的打开模式
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)