Python full stack development, DAY4

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

Python file operation one, the basic process of file operation

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

We write applications in Python or other languages, if we want to save the data permanently, it must be saved on the hard disk, this design to the application to operate the hardware, it is well known that the application can not directly manipulate the hardware, which is the use of the operating system. The operating system encapsulates complex hardware operations into a simple interface for use by users/applications, where files have the concept of a file, and we no longer have to consider the details of the operation of the hard disk, just the process of manipulating the files:

f = open (' a.txt ', encoding= ' utf-8 ')  #打开文件, get the file handle and assign a value to a variable data=f.read ()   #通过句柄对文件进行操作print (data) f.close ()   #关闭文件

Note: A.txt must be present if not present, please create manually, keep and py script in the same directory

Considerations for closing files:

Open a file that contains two parts of the resource: The operating system opens the file + application variable. When you have completed a file, you must recycle the two parts of the file with a non-landed method:

1, F.close () #回收操作系统级打开的文件

2, Del f #回收应用程序级的变量

Where del F must occur after f.close (), otherwise it will cause the operating system open files are 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 a lot of students still do not forget the face of F.close (), for these often forget the classmate, we recommend a fool mode of operation: Use the while keyword to help us manage the context

With open (' A.txt ', ' W ') as F:    Passwith open (' A.txt ', ' R ') as Read_f,open (' B.txt ', ' W ') as Write_f:    data = Read_ F.read ()    write_f.write (data)

  

Ii.. File encoding

F=open (...) is opened by the operating system file, then if we do not specify the encoding, then open the default encoding of the 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 messy, how the file stored in what way, it will open in what way.

F=open (' A.txt ', ' R ', encoding= ' utf-8 ')

  

Iii. 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, file must exist, not present, throw exception"

W, write-only mode "unreadable; not exist" created; empty content "

A, append only write mode "unreadable; not exist" create; "Append content only"

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, image file JGP format, video file avi format)

Rb

Wb

Ab

Note: When opened in B, the content read is a byte type, and a byte type is required for writing, and encoding cannot be specified

3. "+" mode (adds a function)

r+, read and write "readable, writable"

W+b, write read "writable, readable"

A+b, write read "writable, readable"

4. Read/write, read/write, bytes type operation

R+b, read and write "readable, writable"

W+b, write read "writable, readable"

A+b, write read "writable, readable"

Iv. Methods of file operation

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 mobile 0,1,2, of which 1 and 2 must be done in B mode, but regardless of which mode is moved in bytes unit

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

4.2 All methods of operation.

2.x

class file (object) def close (self): # real signature unknown;  Restored from __doc__ close file "" "Close () None or (perhaps) an integer.                 Close the file.  Sets data attribute. Closed to True.  A closed file cannot is used for further I/O operations.  Close () May is called more than once without error.        Some Kinds of File objects (for example, opened by Popen ()) could return an exit status upon closing. "" "Def Fileno (self): # real signature unknown;                 Restored from __doc__ file descriptor "" "Fileno (), integer" File descriptor ".        This is needed for Lower-level file interfaces, such Os.read (). "" "Return 0 def Flush (self): # real signature unknown;  Restored from __doc__ flush file internal buffer "" "Flush () None. Flush the internal I/O buffer. "" "Pass Def Isatty (self): # real signature unknown; Restored from __doc__ to determine if the file is a TTY device "" " Isatty () True or false. True if the file is connected to a TTY device. "" "Return False def Next (self): # real signature unknown; Restored from __doc__ gets the next row of data, does not exist, the error "" "" "" "" "" "" X.next (), the next value, or raise Stopiteration "" "p The Size=none (self, the): # Real signature unknown;                 Restored from __doc__ reads the specified byte data "" "Read ([size]), read at the most size bytes, returned as a string.        If the size argument is negative or omitted, read until EOF is reached.  Notice that while in non-blocking mode, less data than what is requested may be returned, even if no size parameter        was given. "" "Pass Def Readinto (self): # real signature unknown;  Restored from __doc__ read to buffer, do not use, will be abandoned "" "Readinto (), undocumented. Don ' t use this; It may go away. "" "Pass Def ReadLine (self, size=none): # Real signature unknown; Restored from __doc__ read only one row of data """ReadLine ([size]), next line from the file, as a string.  Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line is returned then)        .        Return an empty string at EOF. "" "Pass Def readlines (self, size=none): # Real signature unknown;  Restored from __doc__ reads all data and saves a list of values, "" "ReadLines ([size]), based on line break, and list of strings, each a lines from                 The file.        Call ReadLine () repeatedly and return a list of the lines so read.        The optional size argument, if given, is a approximate bound on the all number of bytes in the lines returned. "" "return [] def seek (self, offset, whence=none): # Real signature unknown;  Restored from __doc__ specifies the position of the pointer in the file "" "Seek (offset[, whence]), None.                 Move to new file position.  Argument offset is a byte count. Optional argument whence defaults to (offsEt from start of file, offset should is >= 0);  Other values is 1 (move relative to position, positive or negative), and 2 (move relative to end of  file, usually negative, although many platforms allow seeking beyond the end of a file).  If the file is opened in text mode, only offsets returned by tell () is legal.        Use of other offsets causes undefined behavior.        Note that not all file objects is seekable. "" "Pass Def Tell (self): # real signature unknown; Restored from __doc__ gets the current pointer position "", "Tell ()", "present file position, an integer (could be a long integer). "" "Pass def truncate (self, size=none): # Real signature unknown;  Restored from __doc__ truncates the data, leaving only the specified previous data "" "Truncate ([size]), None.                 Truncate the file to in the most size bytes.        Size defaults to the current file position, as returned by Tell (). "" "Pass Def write (self, p_str): #Real signature unknown;  Restored from __doc__ write content "" "Write (str)-None.                 Write string str to file.        Note that due to buffering, flush () or close () is needed before the file on disk reflects the data written. "" "Pass Def writelines (self, sequence_of_strings): # Real signature unknown;  Restored from __doc__ writes a list of strings to the file "" "Writelines (sequence_of_strings), None.                 Write the strings to the file.  Note that newlines is not added. The sequence can is any iterable object producing strings.        This is equivalent to calling write () for each string. "" "Pass Def Xreadlines (self): # real signature unknown;                 The restored from __doc__ can be used to read the file line by row, not all "" "Xreadlines ()-returns self. For backward compatibility.        File objects now include the performance optimizations previously implemented in the Xreadlines module.  """      Pass 

3.x

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 G Is 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) # Default 

  

V. Modification of documents

The data of the file is stored on the hard disk, so there is only coverage, there is no IU that said, we usually see the changes in the file, is the effect of simulation, the specific statement 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).

Import  os  #调用系统模块with open (' a.txt ') as Read_f,open ('. A.txt.swap ', ' W ') as Write_f:    data = Read_f.read ()    #全部读入内存, if the file is large, it will be card    data = Data.replace (' Alex ', ' SB ')    #在内存中完成修改    write_f.write (data)     # Write new files once Os.remove (' a.txt ')  #删除源文件os. Rename ('. A.txt.swap ', ' a.txt ')    #将新建的文件重命名为原文件

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

Import Oswith Open (' a.txt ') as Read_f,open ('. A.txt.swap ', ' W ') as Write_f: For line in    Read_f:        line= Line.replace (' Alex ', ' SB ')        

 

Vi. Practice of the day

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.

Exercise Analysis:

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

1. Read the contents of each row first

With open (' A.txt ', ' R ') as F: For line in    F:        #去除字符串左右2边的空格 line        = Line.strip ()        #判断是否为空行        If Len (line) = = 0:            continue        #打印文件内容        print (line)

2. Slice the content, use a space as a separator, use the split () method

With open (' A.txt ', ' R ') as F: For line in    F:        #去除字符串左右2边的空格 line        = Line.strip ()        #判断是否为空行        If Len ( line) = = 0:            continue        #split () slices the string by specifying a delimiter, here is the space        res = Line.split (")        #打印变量        Print (res)

3. Put the data of the list into the specified dictionary

With open (' A.txt ', ' R ') as F: For line in    F:        #去除字符串左右2边的空格 line        = Line.strip ()        #判断是否为空行        If Len ( line) = = 0:            continue        #split () slices the string by specifying a delimiter, where the space        res = Line.split (")        #打印变量        print ({' Name ': res[0], ' price ': res[1], ' Amount ': res[2]})

4. Append the dictionary to an overall list, with the final code as follows:

#总列表result = []with open (' A.txt ', ' R ') as F: For line in    F:        #去除字符串左右2边的空格 line        = Line.strip ()        #判断是否为空行 
   if len (line) = = 0:            continue        #split () slices the string by specifying a delimiter, here is the space        res = Line.split (")        #追加内容        Result.append ({' name ': res[0], ' price ': res[1], ' Amount ': res[2]}) print (result)

  

2, there are the following documents:

Replace all Alex in the file with an uppercase SB.

1. First create a file B.txt, write the content, read the contents of the file.

Since the file is related to Chinese, the code here is Utf-8

With open (' B.txt ', ' R ', encoding= "Utf-8") as F: For line in    F:        #去除字符串左右2边的空格 line        = Line.strip ()        # Determine if the line is empty        if Len = = 0:            continue        #打印文件内容        Print

2. Each row determines if Alex exists, and if so, replace it with the Replace () method

With open (' B.txt ', ' R ', encoding= "Utf-8") as F: For line in    F:        #去除字符串左右2边的空格 line        = Line.strip ()        # Determine if the line is empty if        len (lines) = = 0:            continue        If "Alex" is "in line:"            line.replace ("Alex", "SB")        #打印文件内容        Print (line)

3. Write the contents of the file to a new file and re-read the new file

With open (' B.txt ', ' R ', encoding= "Utf-8") as F,    open (' B.txt.bak ', ' W ', encoding= "Utf-8") as F_new: for line in    F :        #判断是否为空行        If len (line) = = 0:            Continue        #判断一行内容是否包含alex        if "Alex" in line:            #替换文件内容 Line            = Line.replace ("Alex", "SB")        #写入文件内容        f_new.write (line) #读取新文件内容with open (' B.txt.bak ', ' R ', encoding= "Utf-8") as f_red:    for line_red in f_red:        # strips Left and right 2 sides of space        line_red = Line_red.strip ()        Print (line_red)

Python full stack development, DAY4

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.