Python Learning 05-File manipulation

Source: Internet
Author: User

File operations are divided into read, write, modify, in what mode to save files, in what mode encoding open files.

The mode of opening the file is:

    • R, read-only mode (default).
#in what mode to save the file, in what mode encoding to open the file#Example One: R is a text read-only modef = Open (file='d:/Work/part-time contact information. txt', mode='R', encoding='Utf-8')#Absolute Path Accessdata =F.read () f.close ( )#example two: RB: binary read-only mode, unable to specify encoding, because in this mode the data read into memory is directly bytes format, such as to see the content also need to manually decodef = Open (file='Part-time contact information-txt', mode='RB')
    • W, write-only mode. "unreadable; not exist; create; delete content;"
# W mode is to create a new file if the file exists then empty rewrite f = open (file=' part-time. txt', mode='w' , encoding='gbk') f.write (' beauty massage service, phone number: adfs123 ' ) F.close ()
    • A, append mode. "Readable; not exist" create; "only append content;"
# A is the Append mode f= open (' part-time contact information. txt'ab') f.write ( " \ Bai Baiho  Beijing  167  13523230322". Encode ("gbk" )   #  line break append f.close ()

"+" means you can read and write a file at the same time

    • r+, can read and write files. "readable; writable; can be added"
f = open ('Part-time contact information-txt','r+', encoding="GBK") Data=F.read ()Print("content", data) F.write ("\nnewline 1 Teacher") F.write ("\nnewline 2 Teacher") F.write ("\nnewline 3 Teacher") F.write ("\nnewline 4 Teacher")Print("New Content", F.read ())#The result is not read because the cursor has moved to the end after writingf.close ()
    • w+, write and read
#Read- write is opened in the created mode (overwrites the original), can read the content writtenf = open ("Part-time contact information-txt",'w+', encoding="GBK") Data=F.read ()Print("content", data) F.write ("\nnewline 1 Students") F.write ("\nnewline 2 Students") F.write ("\nnewline 3 Students") F.write ("\nnewline 4 Students")Print("New Content", F.read ()) F.close ()
    • A +, with a

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

    • RU
    • R+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)

    • Rb
# RB: Binary read-only mode, unable to specify encoding, because in this mode the data read into memory is directly bytes format, if you want to view the content also need to manually decodef = open (file=' part-time contact information. txt  ', mode='rb')
    • Wb
f = open (' part-time 2.txt','wb')  #  Write binary F.write (" beauty accompany chat!")  ". Encode ("gbk")) f.close ()
    • Ab
f = open (' part-time contact information. txt'ab') f.write ("\ n Bai Baiho  Beijing  167  13523230322". Encode ("gbk"))   #  line break append f.close ()
File operations
f = open ("part-time txt", mode="r+", encoding="GBK") F.fileno ()#returns the index value of the file handle in the kernel, which can be used for IO multiplexingF.flush ()#forcibly flush files from memory buffer to hard diskf.readable ()#Judging whether it is readableF.readline ()#Read Only one line, encountered \ r \ nF.seek ()#moves the cursor of the action file to the specified position (in bytes)F.seek (0)#cursor moves to the beginning of the textf.seekable ()#determine if a file is available for seek operationF.tell ()#returns the current file action cursor position (in bytes)f.truncate ()#truncate a file at a specified length (requires write permission), truncated from the current position of the cursorF.truncate (6)#plus the number is to intercept 6 bytes from the beginning.f.writable ()#determine if the file is writableF.read ()#by character, note and the difference between tell and Seek
File modification
#when modifying a file, move the cursor to the specified position to write the contents to the filef = open (file ='part-time model contact information .', mode='a', encoding='GBK') F.write ("Angela 13988888") F.write ("Snow 167 13324434") F.write ("Liu Lin 166 13828382") F.seek (22)#move cursor to a specified position to insert a fileF.write ("\ n") F.seek (42) F.write ("\ n") F.seek (62) F.write ("\ n") F.seek (0) F.read () f.close ()
The file is modified to occupy the hard disk, reduce memory usage
mport Osf_name="part-time model contact information ."F_new_name="%s.new"%F_nameold_str="Snow"New_str="White Lily"F= Open (f_name,mode='R', encoding='Utf-8') F_new= Open (F_new_name,'W', encoding='Utf-8') forLineinchF:ifOld_strinchLine:line=line.replace (OLD_STR,NEW_STR) f_new.write (line) F.close () F_new.close () os.rename (f_new_name,f_name)#new file replaces old file

Python Learning 05-File manipulation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.