1. Open the file:
#!/usr/local/bin/python3.5filename="Fileop1.file"FD= open (filename,'a', encoding='Utf-8')#mode is read mode by default" "another way to open files with mode when the with code block finishes executing, the internal automatically shuts down and frees the file resource" "with open (filename,'R'As FD: ...
2. File Open mode
Default is read-only mode
'R' #open a file as read-only (default)'W' #Open the file as written to overwrite the existing file'x' #if the file already exists, opening with this mode throws an exception'a' #Open in write mode, append write at the end if the file exists'b' #open a file in binary mode'T' #Open in text mode (default)'+' #Read-write mode (can be added to other modes for use)'U' #Universal line break support
R read-only, r+ read/write, not created
W New write-only, w+ new read-write, both will clear the contents of the file 0
a,a+ additional mode open a: Additional write mode open, unreadable; A +: additional read and write mode open
The difference between w+ and r+:
r+: Readable and writable, if the file does not exist, error; w+: Readable and writable, if the file does not exist, create;
The difference between r+ and A +:
r+ The default pointer position will overwrite before the content is present
Non-readable open mode: W and a
How to open a new file if it does not exist: a,a+,w,w+
3. File read and write operations
Fd.read () Fd.write ()
Read by line:
for inch FD: Print (line) # convert the file into an iterator that doesn't keep the data in memory, it's safer and more efficient
Operation file read-write pointers:
F.tell () # Returns the position of the pointer f.read (n) # read N, the pointer also moves how many f.seek () # 0 Return file Initial
4.flush method
F.flush () # Force flush to hard disk # progress bar Method:import sys,timefor in Range (Ten): sys.stdout.write ("#") Sys.stdout.flush () Time.sleep (0.1)
5.truncate method
F.truncate (n) # truncate n characters from the beginning, and the rest to erase
Python file Operations