Python Full Stack Learning summary four: file operations

Source: Internet
Author: User
Tags readable readline

A file Operation step

1 Open a file, get a handle to the file and assign a value

2 manipulating files with a handle

3 Closing files

The essence of the file operation is: read the file into memory, can be viewed in memory, modify, copy, and so on, if the file has been re-modified delete operations, it is re-written to the hard disk, not on the original hard disk file operation!

Two-File Operation example

1 reading files

f = open ('Test','R', encoding='Utf-8')#data = F.read () #读取文件所有的内容#print (f.readable ()) #查询文件是否可以读取#print ("First line", F.readline (). Rstrip (' \ n ')) #读取文件一行, removing the newline flag from the last line#print ("Second row", F.readline (). Rstrip (' \ n ')) #文件一次读取一行, unread, the cursor will record the read position#print ("Third line", F.readline (). Rstrip (' \ n '))#Print ("line Fourth", F.readline (). Rstrip (' \ n '))#print ("line Fifth", F.readline (). Rstrip (' \ n '))#Print ("line Sixth", F.readline (). Rstrip (' \ n ')) #文件已经读完, the cursor moves last, so the content cannot be read#Print ("line Seventh", F.readline (). Rstrip (' \ n '))Print(F.readlines ())#Read all the contents of the file, including the return key is also read outF.close ()

As above: file read operation mainly has the above function readable (): Query whether the file can read ReadLine (): Read the file line, the end of the newline flag readlines () Read all the memory, including newline, stored in a list. Read () reads all characters by default, and if a parameter such as read (10) reads 10 characters

2 Write file operations

f = open ('Test','W', encoding='Utf-8')Print(F.writable ()) F.write ('riding a donkey chasing a car')#the written content must be a stringF.writelines (['1111111\n','222222\n',' set sail']) f.close ()

As above: the Write () operation is to write a string to the file, write must be a string, writeable () query whether the file is writable, Writelines () writes the contents of the list, the memory in the list is a string element

3 Append mode operation

#f = open ("Test", ' a ', encoding= ' utf-8 ')#f.write (' \ n Test append ')#f.close ()F= Open ("Test",'r+', encoding='Utf-8')#open file, can writeF.write ('\ n Test read/write')#Write from the cursor position to start writing, first open, default from the first line to writeF.close ()

As above: A indicates a write operation based on the source file.

In addition to the ' R ', ' W ', ' A ' mode is also ' x ' mode, the x mode and W mode are different mainly x is the write operation source file does not exist, then error, and W does not exist then create, if there is a source file contents are emptied.

The ' r+ ' mode is opened as read and can be written

' w+ ' mode is written to open, can be read operation

' A + ' mode is open in Append mode and can be read operation

The ' B ' mode is to read and write in binary form, such as ' RB ', ' rb+ ', ' WB ', ' wb+ ' and so on, the default action is in the form of text.

Winddow system mainly has the form of text and binary (byte) operation, the essence of the underlying is to convert the text string into binary, and the Linux system is in binary form operation

Binary operation without specifying encoding

f = open (' Test ', ' RB ')

42 binary operation

#f = open (' Binary test ', ' WB ')#f.write (' binary test read-write operation \ n '. Encode (' Utf-8 ')) #通过字符串方法encode进行编码操作, written to text#f.write (bytes (' Byte convert form operation ', encoding= ' Utf-8 ')) #通过字符串操作函数bytes操作, write to text with Utf-8 encoding, and manipulate text#f.close ()F= Open ('Binary Testing','RB') Data=F.read ()Print(Data.decode ('Utf-8'))#The readout data is binary encoded, the decoding operation is done by means of decode, the string is printed outF.close ()

The encoding cannot be specified in the binary operation mode, while note that the carriage return behavior in the window system is \ n in the \r\n,linux system

Text string-----"encode--------> Binary encoding

Binary coded-----"decode--------> Text strings

Binary encoding is done in the following ways:

' String '. Encode (' Utf-8 ')

Bytes (' String ', encoding= ' utf-8 ')

The ways to decode the binary are:

' Binary encoding '. Decode (' Utf-8 ')

5 file other Operational functions summary

Read (3) represents the reading of 3 characters, the rest of the files within the cursor movement are in bytes such as seek,tell,read,truncate operations

F.flush () #把文件内容从内存刷到硬盘中, play a role in real-time preservation.

f.closed# If the file is closed, returns true

f.encoding# viewing the encoding format of open files using the, note that not the actual encoding format of the file

F.tell #查看文件处理当前的光标位置

F.seek (3) #从头开始运算, move the cursor to the third byte

F.truncate #从头开始运算, files are kept only from 0-10 bytes of content, and the file must be opened in writing, except for ' W ' and ' w+ '.

6 advanced application of the Seek method

Seek a total of 2 parameters, the first parameter is the number of cursors, the second parameter defaults to 0, the default is 0 o'clock, the number of cursors is counted from the beginning.

When the second argument is 1 o'clock, the cursor is relative from the last position operation.

When the second argument is 2 o'clock, the cursor starts counting backwards, for example, F.seek ( -5,2), which reads from 5 characters from the front of the tail

For example, read the last line of the operation log.

With open ('Log','RB') as F: forIinchF:#when reading a file, it is recommended to read one line at a time, saving memoryoffset =-10 whileTrue:f.seek (offset,2)#insert cursor starting at taildata = F.readlines ()#read it Out is a list            ifLen (data) > 1:                Print(Data[-1].decode ('Utf-8'))                 BreakOffset*= 2

Python full Stack learning summary four: file operations

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.