Operation of Python files

Source: Internet
Author: User
Tags bit set readable throw exception

One, the basic process of file operation.

The computer system is divided into three parts: the hardware, the operating system and the application.

Applications that we write in Python or other languages need to be saved on the hard drive if we want to keep the data permanently, which involves the application operating hardware, and it is well known that the application is not able to manipulate the hardware directly. The operating system encapsulates complex hardware operations into a simple interface for use by the user/application, where the file is the operating system provided to the application to manipulate the virtual concept of the hard disk, and the user or application can save its own data permanently by manipulating the file.

With the concept of a file, we no longer have to consider the details of the operation of the hard disk, just the process of manipulating the files:

#1. Open the file, get the file handle and assign a value to a variable f=open (' A.txt ', ' R ', encoding= ' Utf-8 ') #默认打开模式就为r #. Manipulate the file through a handle data=f.read () #3. Close File F.close ()
Considerations for closing files:
Open a file that contains two parts of the resource: an operating system-level Open file + Application variable. When a file is completed, the two parts of the file must be recovered in a non-landed manner: 1, F.close () #回收操作系统级打开的文件2, Del f #回收应用程序级的变量其中del f must occur after f.close (), Otherwise it will cause the operating system to open the file is not closed, the use of resources, and Python automatic garbage collection mechanism determines that we do not have to consider Del F, which requires us, after the completion of the file, we must remember F.close () although I say so, But many students will not forget the face of F.close (), for those who do not long brain, we recommend a fool mode of operation: Use with the keyword to help us manage the context with open (' A.txt ', ' W ') as F:    Pass with Open (' A.txt ', ' R ') as Read_f,open (' B.txt ', ' W ') as Write_f:    data=read_f.read ()    write_f.write (data) note
Two, file encoding

F=open (...) is opened by the operating system file, then if we do not specify the encoding for open, then the default encoding of the opening file is obviously the operating system, the operating system will use its own default encoding to open the file, under Windows is GBK, under Linux is Utf-8.

#这就用到了上节课讲的字符编码的知识: To ensure that it is not garbled, how the file stored in what way, it will open in what way. F=open (' A.txt ', ' R ', encoding= ' utf-8 ')
Three, open mode of the file

File handle = open (' File path ', ' mode ')

#1. The mode of opening the file has (default is text mode): R, read-only mode "default mode, the file must exist, does not exist" throw exception "W, write-only mode" is not readable, does not exist, it is empty content "A, append write mode only" unreadable, does not exist, then only append the content "#2. For non-text files, we can only use B mode, "B" means to operate in bytes (and all files are stored in bytes, using this mode regardless of the text file character encoding, picture file JGP format, video file avi format) RB Wbab Note: When opened in B mode, Read to the content is a byte type, write also need to provide byte type, can not specify the encoding # #, ' + ' mode (is added a function) r+, read and write "readable, can write" w+, write read "writable, readable" A +, write read "writable, readable" #4, to bytes type of operation of Read and write, read, Write read mode r+b, read and write "readable, can write" w+b, write read "writable, readable" a+b, write read "writable, readable"
Four, the file operation method. 4.1 Common methods of operation.

Read (3):

1. When the file is opened in text mode, the representation reads 3 characters

2. When the file is opened in B mode, the delegate reads 3 bytes

The rest of the files within the cursor movement are in bytes such as: seek,tell,truncate

Attention:

1. Seek has three modes of movement 0,1,2, of which 1 and 2 must be performed in B mode, but regardless of which mode is moved in bytes units

2. Truncate is a truncated file, so the file must be opened in a way that can be written, but not with W or w+, etc., because the file is directly emptied, so truncate to r+ or a or a + and other modes to test the effect.

4.2 All methods of operation.
Class Textiowrapper (_textiobase): "" "Character and line based layer over a Bufferediobase object, buffer. Encoding gives the name of the encoding that the stream would be a decoded or encoded with.        It defaults to Locale.getpreferredencoding (False). Errors determines the strictness of encoding and decoding (see Help (Codecs.        CODEC) or the documentation for Codecs.register) and defaults to "strict". NewLine controls how line endings is handled.  It can be None, ', ' \ n ', ' \ R ', and ' \ r \ n '. It works as follows: * on input, if newline are None, universal newlines mode is enabled.      Lines in the input can end in ' \ n ', ' \ R ', or ' \ r \ n ', and these is translated into ' \ n ' before being returned to the Caller. If it is ", universal newline mode is enabled, but line endings was returned to the caller untranslated. If it has any of the other legal values, input lines is only terminated by the given string, and the line Endin E +s returned to the caller untranslated. * On output, if newline was None, any ' \ n ' characters written is translated to the system default line separator, OS. Linesep. If newline is ' or ' \ n ', no translation takes place.        If NewLine is any of the other legal values, any ' \ n ' characters written is translated to the given string.    If line_buffering is True, a call to flush was implied when a call to write contains a newline character. "" "Def Close (self, *args, **kwargs): # Real Signature unknown close file pass def fileno (self, *args, **kwa        RGS): # Real Signature Unknown file descriptor pass def flush (self, *args, **kwargs): # Real Signature Unknown Flush file Internal Buffer pass Def isatty (self, *args, **kwargs): # Real Signature Unknown determine if the file is consent to TTY device pas S def read (self, *args, **kwargs): # Real Signature Unknown read specified byte data pass def readable (self, *args, * *      Kwargs): # Real Signature Unknown  Readable pass def readline (self, *args, **kwargs): # Real Signature Unknown read only one row of data pass Def Seek (Self, *args, **kwargs): # Real signature Unknown specify pointer position in file pass Def seekable (self, *args, **kwargs): # r EAL signature Unknown pointer is operable pass DEF tell (self, *args, **kwargs): # Real signature unknown get pointer bit Set Pass Def truncate (self, *args, **kwargs): # Real Signature Unknown truncate data, retain only specified before data pass def WR Itable (self, *args, **kwargs): # Real Signature unknown can write pass def write (self, *args, **kwargs): # rea L Signature Unknown Write content pass def __getstate__ (self, *args, **kwargs): # Real signature unknown pas    S def __init__ (self, *args, **kwargs): # Real Signature Unknown pass @staticmethod # known case of __new__  def __new__ (*args, **kwargs): # Real signature Unknown "" "Create and return a new object. See Help (type) for accurate signature.    """    Pass Def __next__ (self, *args, **kwargs): # Real signature Unknown ' "" Implement Next (self). "" "        Pass Def __repr__ (self, *args, **kwargs): # Real signature Unknown ' "" Return repr (self). "" " Pass Buffer = Property (Lambda self:object (), Lambda Self, v:none, lambda Self:none) # Default closed = Property ( Lambda Self:object (), Lambda Self, v:none, lambda self:none) # Default encoding = property (Lambda self:object (), L Ambda self, V:none, lambda self:none) # Default Errors = Property (Lambda self:object (), Lambda Self, v:none, LAMBD A self:none) # Default Line_buffering = Property (Lambda self:object (), Lambda Self, v:none, Lambda Self:none) # D Efault Name = Property (Lambda self:object (), Lambda Self, v:none, lambda self:none) # default newlines = Propert Y (Lambda self:object (), Lambda Self, v:none, lambda self:none) # Default _chunk_size = Property (Lambda self:object (), Lambda Self, v:none, lambda self:None) # Default _finalizing = Property (Lambda self:object (), Lambda Self, v:none, Lambda Self:none) # default3.x 
Five, file modification.

File data is stored on the hard disk, so there is only coverage, there is no modification so to speak, we usually see the modified files, are simulated out of the effect, specifically, there are two ways to achieve:

Mode one: The contents of the file stored in the hard disk are loaded into memory, can be modified in memory, and then overwritten by memory to the hard disk (word,vim,nodpad++ and other editors).

Method One

Mode two: The contents of the file stored on the hard disk are read into memory line by line, the modification is completed to write a new file, and finally overwrite the source file with a new file

Method TwoSix, the same day practice.

1. File a.txt content: Each line content is the product name, the price, the number.

Apple 10 3

Tesla 100000 1

MAC 3000 2

Lenovo 30000 3

Chicken 10 3

By code, build it into this data type: [{' name ': ' Apple ', ' price ': ' Amount ': ' 3},{' name ': ' Tesla ', ' price ': 1000000, ' Amount ': 1} ...] and calculate the total price.

2, there are the following documents:

-------

Alex is the old boy Python initiator, creator.

Alex is actually a tranny.

Who says Alex is SB?

You guys are so funny, Alex, you can't hide the temperament of senior cock silk.

----------

Replace all Alex in the file with an uppercase SB.

Operation of Python files

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.