Basic Python Tutorial (second edition) Learning note files and materials (11th)
Open File:
Open (Filename[,mode[,buffering]])
Mode is the pattern of reading and writing files
F=open (R ' c:\somefile.txt ') #默认是读模式
+ means can read and write, R read mode, W write mode, a append mode, b binary mode;
The newline character is \ r \ n in Windows, and in Unix, Python is automatically converted;
Buffering buffer, 0 for unbuffered, 1 for buffering (use flush or close to write to hard disk);
Sys.stdin standard input; sys.stdout standard output; Sys.stderr error message;
F=open (' Aaa.txt ', ' W ')
F.write (' Hello, ')
F.write (' world! ')
F.close ()
F=open (' Aaa.txt ', ' R ')
F.read (4) # read 4 characters
F.read () # reads the rest of the content
Pipe input/output
Text=sys.stdin.read ()
F.readline () reads a line
F.readline (5) Read 5 character (s)
F.readlines () reads all rows and returns as a list
The f.writelines () input parameter is a list that writes the contents to a file, and no new rows are added;
Close File F.close ()
With open (' Aaa.txt ') as Somefile:
Do_something (Somefile)
Processing by byte
F=open (filename)
Char=f.read (1)
Wile Char:
Process (char)
Char=f.read ()
F.close ()
F=open (filename)
While True:
Char=f.read (1)
If not char:break
Process (char)
F.close ()
Line-by-row processing
F=open (filename)
While True:
Line=f.readline ()
If not line:break
Process (line)
F.close ()
Iterate through each character with read
F=open (filename)
For Char in F.read ():
Process (char)
F.close ()
Iterate rows with ReadLines
F=open (filename)
For line in F.realines ():
Process (line)
F.close ()
Lazy line iterations for large file implementations
Import Fileinput
For line in Fileinput.input (finename):
Process (line)
Iterate files
F=open (filename)
For line in F:
Process (line)
F.close ()
Basic Python Tutorial (second edition) Learning note files and materials (11th)