文件

文件
1、打开文件
要打开文件,可使用函数open,它位于自动导入的模块io中。函数open将文件名作为唯一必不可少的参数,并返回一个文件对象。若文件位于其它地方,可指定完整的路径。
>>>f = open("filename.txt")
>>>f = open("/path/to/somewhere/filename.txt")
若要通过写入文本来创建文件,则需要函数open的第二个参数。
文件模式
调用函数open时,如果只指定文件名,将获得一个可读取的对象。如果要写入文件,必须通过指定模式来显式的指出。函数open的参数mode的取值可能有多个。
r ---读取模式(默认模式)
w ---写入模式
x ---独占写入模式
a ---附加模式
b ---二进制模式(与其它模式结合使用)
t ---文本模式(默认值,与其它模式结合使用)
+ ---读写模式(与其它模式结合使用)
说明:
显式的指定读取模式的效果与跟本不指定模式相同;
写入模式能够写入文件,并在文件不存在时创建它;
独占写入模式更进一步,在文件已经存在时引发FileExistsError异常;
在写入模式下打开文件时,既有内容将被删除(截断),并从文件开头处开始写入;
如果要在既有文件末尾继续写入,可使用附加模式;
"+"可与其它任何模式结合使用,表示既可读取也可写入。如要打开一个文本文件进行读写,可使用"r+"。("r+"和"w+"的区别:后者截断文件,而前者不会)
默认模式为"rt",这意味着将把文件视为经过编码的unicode文本,因此将自动进行编码和解码,且默认使用UTF-8编码。
要指定其它编码和Unicode错误处理策略,可使用关键字参数encoding和errors。这还将自动转换换行字符。默认情况下,行以"\n"结尾。读取时将自动替换其它行尾字符("\r"或"\r\n");写入时将"\n"替换为系统的默认行尾字符(os.linesep)
python使用通用换行模式。在这种模式下,readlines等方法能够识别所有合法的换行符("\n"、"\r"和"\r\n")。如果要使用这种模式,同时禁止自动转换,可将关键字参数newline设置为空字符串,如open(name,newlin='')
如果文件包含非文本的二进制数据,如音频或图像,肯定不希望执行自动转换,为此,可使用二进制模式(如"rb")来禁止与文本相关的功能。
2、文件的基本方法
文件对象的一些基本方法以及其他类似于文件的对象(有时也称为流)。类似于文件的对象支持文件对象的一些方法,如支持read或write。
三个标准流:
一个标准数据输入源是sys.stdin:当程序从标准输入读取时,可以通过输入来提供文本,也可使用管道将标准输入流关联到其它程序的标准输出
提供给print的文本出现在sys.stdout中,向input提供的提示信息也出现在这里。写入到sys.stdout的数据通常出现在屏幕上,也可使用管道将其重定向到另一个程序的标准输入。
错误消息(如栈跟踪)被写入到sys.stderr,但与写入到sys.stdout的内容一样,可对其进行重定向。
读取和写入
若有个名为f的类似于文件的对象,可使用f.write来写入数据,f.read来读取数据。在文本和二进制模式下,基本上分别将str和bytes类用作数据。
>>>f = open("filename.txt")
>>>f.write("hello,")
6
>>>f.write("world")
11
>>>f.close()
注:使用完文件后,调用了方法close
>>>>f = open("filename.txt","r")
>>>f.read(4) --->'hell'
>>>f.read() --->'o,world!.....'
注:首先指定了要读取多少个(4)字符,接下来读取了文件余下的全部内容(不指定要读取多少个字符)。
若在二进制模式下是读取多少字节。
调用函数open时,可以不指定模式,因为其默认值就是"r"
使用管道重定向输出:
随机存取
读取文件中的任意部分:可以使用文件对象的两个方法:seektell
seek(offset9,whence):将当前位置(执行读取或写入的位置)移到offset和whence指定的地方。参数offset指定了字节(字符)数,而参数whence默认为io.SEEK_SET(0),这意味着偏移量是相对于文件开头的(此时偏移量不能为负数)。参数whence还可设置为io.SEEK_CUR(1)或io.SEEK_END(2),其中前者表示相对于当前位置进行移到(偏移量可以为负),而后者表示相对于文件末尾进行移动。
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt',"w")
>>>f.write("0123456789abcdefghij")
20
>>>f.seek(5)
5
>>>f.write("hello,world")
11
>>>f.close()
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt')
>>>f.read() --->'01234hello,worldghij'
方法tell()返回当前位于文件的什么位置:
>>>>f = open(r'C:\Users\Administrator\Desktop\test.txt')
>>>f.read(3) --->'012'
>>>f.read(2) --->'34'
>>>f.tell() --->'5'
读取行和写入行:
成行的读取:可以使用方法readline。调用这个方法时,可以不提供任何参数(该情况下,将读取一行并返回它);也可提供一个非负整数,指定readline最多可读取多少个字符。
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt')
>>>f.readline()
要读取文件中的所有的行,并以列表的方式返回,可使用方法readliness
方法writeliness与readliness相反:接受一个字符串列表(也可是任何序列或可迭代对象),并将这些字符串都写入到文件(或流)中。写入时不会添加换行符,因此需自行添加。另没有方法writeline,因为可使用write。
关闭文件:
关闭文件:调用方法close。通常程序退出时将自动关闭文件对象。
对于写入过的文件,一定要将其关闭,因为Python可能会缓冲写入的数据。若程序因某种原因崩溃,数据可能根本不会写入到文件中。
如果要重置缓冲,让所做的修改反映到磁盘中,但又不想关闭文件,可使用方法flush(然flush可能出于锁定考而禁止其它正在运行的程序访问这个文件)。
要确保文件得以关闭,可使用一条try/finally语句,并在finally子句中调用close。
#打开某文件
try:
#将数据写入到文件中
finally:
file.close()
另:有一条专门为此设计的语句:with语句
with open("somefile.txt") as somefile
do_something(somefile)
with语句能够打开文件并将其赋给一个变量(此处是somefile)。到达语句末尾时,将自动关闭文件,即便出现异常亦是如此。
示例:有一文本内容为:
this is first line
this is second line
this is three line
read(n)的使用:
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt')
>>>f.read(7) --->'this is fi'
>>>f.read(5) --->'rst l'
>>>f.close()
read()的使用:
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt')
>>>print(f.read())
this is first line
this is second line
this is three line
>>>f.close()
readline()的使用:
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt')
>>>for i in range(3):
print(str(i) + ":" + f.readline(),end="")
0:this is first line
1:this is second line
2:this is three line
>>>f.close()
readlines()的使用:
>>>import pprint
>>>pprint.pprint(open(r'C:\Users\Administrator\Desktop\test.txt').readlines())
['this is first line\n',
'this is second line\n',
'this is three line\n']
注:此处利用了文件对象将被自动关闭。
write(string)的使用:
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt',"w")
>>>f.write("there\nis no\nmarket")
>>>f.close()
文件文本内容将变为:
there
is no
market
writelines(list)的使用:
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt')
>>>lines=f.readlines()
>>>f.close()
>>>lines[1] = "isn't a\n"
>>> lines --->['there\n', "isn't a\n", 'market']
>>>f = open(r'C:\Users\Administrator\Desktop\test.txt',"w")
>>>f.writelines(lines)
>>>f.close()
文件文本内容将变为:
there
isn't a
market
3、迭代文件内容
对每个字符或行所做的处理
def process(string)
print("Processing: ",string)
每次一个字符/字节:
使用read遍历字符:
with open(filename) as f:
char = f.read(1)
while char:
process(char)
char = f.read(1)
注:在文件末尾时,方法read将返回一个空字符串,即结束循环。在此之前,char都只包含一个字符,对应的布尔值为True。
with open(filename) as f:
while True:
char = f.read(1)
if not char:break
process(char)
每次一行:
在while循环中使用readline
with open(filename) as f:
while True:
line = f.readline(1)
if not line:break
process(line)
读取所有的内容:
一次读取整个文件:可使用方法read并不提供任何参数(将整个文件读取到一个字符串中),或使用方法readlines(将文件读取到一个字符串列表中,其中每个字符串都是一行)
使用read迭代字符:
with open(filename) as f:
for char in f.read():
process(char)
使用readlines迭代行:
with open(filename) as f:
for line in f.read():
process(line)
fileinput实现延迟行迭代:
迭代大型文件中的行,使用readlines将占大量内存。也可结合使用while和readline,在python中,应首选for循环。另可使用一种延迟行迭代的方法--只读取实际需要的文本部分。
使用fileinput迭代行:
import fileinput
for line in fileinput.input(filename)
process(line)
文件迭代器
文件实际上也是可迭代的,可在for循环中直接使用它们来迭代行。
with open(filename) as f:
for line in f:
process(line)
在不给文件对象赋值给变量的情况下迭代文件:
for line in open(filename)
process(line)
要迭代标准输入sys.stdin中的所有行:
import sys
for line in sys.stdin:
process(line)
对文件:如使用list(open(filename))将其转换为字符串列表,其效果与使用readlines相同
>>>f = open("somefile","w")
>>>print("first","line",file=f)
>>>print("second","line",file=f)
>>>print("third","and final","line",file=f)
>>>f.close()
>>>lines=list(open("somefile"))
>>>lines --->['first line\n', 'second line\n', 'third and final line\n']
>>>first,second,third = open("somefile")
>>>first --->'first line\n'
>>>second ---> 'second line\n'
>>>third --->'third and final line\n'
注:使用了print来写入文件,这将自动在提供的字符串后面添加换行符
对打开的文件进行序列解包,从而将每行存储到不同的变量中
posted @ 2018-08-06 21:11  Sky-wings  阅读(309)  评论(0编辑  收藏  举报