version:Python 3.3.2
Python用open()返回一个文件,最常用的open函数是open(filename , mode)
其中,mode包括有"w"(write), “r”(read) , “a”(open the file for appending), 当然也可以用“wt”表示写入text,“rt”表示读取text;
file.readline()可以一次读取文件中内容的一行
* 每次文件操作完成之后,一定要加上file.close()函数将文件关闭。
>>> strings = """\I'm a great man who was born in China I was born to give and give and give This is a new line And this is another new line""" >>> file.write(strings) 123 #此处表示写入的内容总共有多少byte >>> file.close()
我们可以调用read()函数将文件的内容打印出来,但是当read()之后,当前的位置将停留在末尾也就是文字的最后位置,如果这时候想再次打印文件内容,调用read()函数将得到空的内容,可行的办法之一是将文件关闭再重新打开,当然我们也有一些新的办法来简化此操作。
>>> file = open("output.txt","rt") >>> print(file.read()) \I'm a great man who was born in China I was born to give and give and give This is a new line And this is another new line >>> print(file.read()) #这里将会是空白,因为此刻指针(光标)的位置处于段落末尾
1. seek()
seek可以用来改变当前object的位置(例如file read之后),通常的格式seek(offset, from_what)。
The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.
默认只有一个参数,就表示从文件开始的位置(0),因此,seek(0)就表示目前是处于文件的开头,第二个参数表示从哪里开始计算,0表示开头,也是默认的,1表示当前位置,2表示末尾。
>>> file.seek(0) 0#当前位置 >>> print(file.read()) \I'm a great man who was born in China I was born to give and give and give This is a new line And this is another new line
2. 利用list,将file中的文字存入到list中
file有一个函数readlines(),注意此函数和readline()有区别,readline是一次读取一行,而readlines()是将所有数据存入list中,每一行作为list的一个element,如此之后,即便我们close的文件,依旧可以继续打印文件里已经存储在list中的内容了。
>>> x = file.readlines()#错误,注意此时的位置已经处于末尾了 >>> print(x) []#所以打印出来的内容为空 >>> print(x[0]) Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> print(x[0]) IndexError: list index out of range >>> file.seek(0)#将位置置于开头 0 >>> x = file.readlines() >>> print(x) ["\\I'm a great man who was born in China\n", 'I was born to give and give and give\n', 'This is a new line\n', 'And this is another new line'] >>> print(x[0])#打印list的各项内容 \I'm a great man who was born in China >>> file.close()#即便关闭了file,也可以继续操作,因为内容已经存储到了list中 >>> print(x[0]) \I'm a great man who was born in China >>> print(x[3]) And this is another new line >>>代码中我犯了一个错误,第一次没有将位置seek到开头,所以第一次没有将lines存入到x中,也就是说,若想把每一行存入到list中,也需要将当前位置置于0