(二)2-5 文件操作

文件操作
Python提供了标准输入和输出进行读写。
a、读取文件内容
当前目录下有个text.txt,文件内容如下:
11111
22222
33333
44444
55555
编写text.py ,内容如下:
readlines()方法:读取文件内容,文件内容的每一行都是一个字符串,最后返回一个字符串。
import codecs
f = codecs.open('text.txt')
print(f.readlines())
f.close()
运行结果:
['11111 ', '22222 ', '33333 ', '44444 ', '55555 ']
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

readline() 读取文件一行内容
next() 读取文件下一行内容返回一个字符串


打开文件步骤:
1、open文件
2、文件操作(读或者写)
3、关闭文件

import codecs
f = codecs.open('text.txt')
text = f.read()
print(type(text))
f.close()
运行结果:
<type 'str'>
对字符串操作
import codecs
f = codecs.open('text.txt')
text = f.read()
print(type(text))
result = text.replace('1','A')
print(result)
f.close()
<type 'str'>
AAAAA
22222
33333
44444
55555

codecs 这个模块主要是用来解决文件乱码问题
open(filename,mode)
mode 有几个参数需要注意,
r 读
w 写
b 二进制
a 追加
write() 必须传入字符串
writelines() 必须传入一个序列
import codecs
f = codecs.open('2.txt','ab')
f.write("hello world!! ")
f.write("hello 11111!! ")
f.write("hello 22222!! ")
f.write("hello 33333!! ")
f.write("hello {}!! ".format("cnblogs"))
f.write("hello %s!! " % "cnblogs")
f.close()

file常用方法(上)
读取文件
f = open("3.txt",'rb')
print(dir(f))
print(f.readlines())
f.close()
运行结果:
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
['hello world!! ', 'hello 11111!! ', 'hello 22222!! ', 'hello 33333!! ', 'hello world!! ', 'hello 11111!! ', 'hello 22222!! ', 'hello 33333!! ', 'hello cnblogs!! ', 'hello cnblogs!!']

file常用方法(下)
import codecs
f = codecs.open('file1.txt','wb')
print(dir(f))
f.write('hello world! cnblogs ')
print(f.tell())
f.writelines(['aaa ','bbb ','ccc ','ddd ','ddd '])
print(f.tell())
f.seek(0)
f.write('this is python!!!!!!!!!!!!')
f.close()
运行结果:
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
21
41
file1.txt文件内容:
this is python!!!!!!!!!!!!bb
ccc
ddd
ddd

扩展:
f.name 查看文件的名字
f.closed 布尔值,判断文件是否关闭
f.encoding() 查看文件的编码
f.mode 查看文件的打开模式

file的with用法
import codecs
with codecs.open("text.txt","rb") as f :
# print(f.readlines)
print(f.read())
print(f.closed)
print(f.closed)
运行结果:
11111
22222
33333
44444
55555
False
True
text.txt文件内容:
11111
22222
33333
44444
55555
打印带行号的文件
with codecs.open("text.txt","rb") as f:
for line,value in enumerate(f):
print(line,value)
运行结果:
(0, '11111 ')
(1, '22222 ')
(2, '33333 ')
(3, '44444 ')
(4, '55555')

读取指定文件行的内容:
import linecache
count = linecache.getline(filename,linenum)

import linecache
count = linecache.getline("text.txt",4)
print(count)
运行结果:
44444

with方法在我们平时工作中非常重要,简单方便,支持快速开发,不需要考虑文件关闭的情况,codecs模块用来解决文件乱码

原文地址:https://www.cnblogs.com/pythonlx/p/7745539.html