Welcome to no pain no gain, we is learning together!!
Files and Streams
Open file is used in Python3, python2.x is
Open (Name[,mode[,buffering]])
Mode: ' R ' read mode
' W ' write mode
' A ' Append mode
' B ' binary mode
' r+ ' equates to ' r+a '
' w+ ' equates to ' w+r '
' A + ' equates to ' a+r '
The buffering parameter is 0 or FALSE, which indicates no buffer and directly operates on the hard disk.
The parameter is 1 or true, which means that the program is faster by using memory
The parameter is greater than 1, which indicates the size of the buffer (in bytes)
-1 or negative, indicating the size of the default buffer
Operation: F = open (' Somefile.txt ') #默认的打开模式是read
f = open (' Somefile.txt ', ' W ')
F.write (' Hello, ') #会提示写入字符的个数
F.write (' World ')
F.close () #如果文件存在, directly overwrites the first content, then writes, if it is written, the new
f = open (' Somefiles.txt ', ' R ') # ' R ' mode is the default mode and can not be added
F.read (4) # tells the stream to read 4 characters (bytes), which will output the first four characters
F.read () #读取剩余的部分, output the remaining characters
F.close ()
Tubular output: $cat somefile.txt | Python somescript.py | Sort
#somescript. py
Import Sys
Text = Sys.stdin.read ()
Words = Text.split ()
WordCount = Len (words)
print ' Wordcount: '. WordCount
The previous examples are handled from the beginning of the flow. You can use Seek and tell to deal with parts of interest.
Seek (Offset[,whence]):
whence = 0 #表示偏移量是在文件的开始进行
whence = 1 #想当与当前位置, offset can be negative
whence = 2 #相对于文件结尾的移动
f = open (R ' a.txt ', ' W ')
F.write (' 0123456789 ')
F.seek (5)
F.write (' Hello World ')
f = open (R ' a.txt ')
R.read ()
' 01234hello world ... ' #会在第五的位置开始写.
f = open (' A.txt ')
F.read (3)
' 012 '
F.read (2)
' 34 '
F.tell ()
5l #告诉你在当前第五的位置
F.readline #读取一行
F=open (' A.txt ')
For I in range (3):
Print str (i) + ': ' + f.readline ()
0: ...
1: ...
2: .....
3: .....
F.readlines #全部读取
F.writeline ()
F.writelines ()
Closing of files:
Close files to avoid using quotas for files that are open in your system
If you want to make sure that the file is closed, you can use the Try/finally statement and call Close () in finally
Method:
Open your file here
Try
Write data to your file
Finally
File.close ()
There are actually statements designed specifically for this situation, both with statements
With open (' Someone.txt ') as Somefile:
Do Something (someone.txt)
#把文件负值到 the somefile variable,
If the file is in memory and is not written to the file and you want to see the contents in the file, you need to use the Flush method
Python---file processing