Python Learning Note: basic Day03

Source: Internet
Author: User

I. File operations

The ability to read and write files on a magnetic disk is provided by the operating system, and the modern operating system does not allow normal programs to manipulate disks directly. Therefore, the read-write file is the request operating system to open a file object (often referred to as a file descriptor), and then, through the interface provided by the operating system to read data from this file object (read the file), or write the data to this file object (write file ).

1. Read the file

To open a file object in read-file mode, use the Python built-in open () function to pass in file names and identifiers.

$ cat test.txt$ This is a file
$ life was short
$ use python------------------------f = open ("Test.txt", ' R ') #打开test. txt file

After the file is opened successfully, the contents of the file are read, and we can use read () to read the contents of the file into memory at once.

Print (F.read ()) >>this is a file>>life is Short>>use python

The call to read () reads the entire contents of the file one time, as well as the ReadLines (), reads the file into memory at once and returns a list line by row, and if a large file is read, the memory may not be able to hold up, because the target can be reached by repeatedly calling read (size). , of course, you can also read the file line-by-row into memory.

For line in F:    print (Line.strip ()) >>this are a file>>life is Short>>use python

This approach is equivalent to ReadLine (), which is more efficient for large file processing. However, when memory is sufficient to open a finished file, read () and ReadLines () are more efficient, and readlines () is more appropriate for the configuration file.

    Therefore, we need to choose the best way to do the reading according to different situations.

The final step in the file operation is to call the close () method to close the file, which must be closed after the file is used, because the file object consumes the resources of the operating system and the number of files that the operating system can open at the same time is limited.

    Of course, in order to avoid forgetting to close a file at some point, Python provides a more brief introduction to how the file is opened--with statements.

With open ("Test.txt", ' R ') as F:    print (F.read ())

2. Writing files

    Write and read files are the same, the only difference is that when a function is called, an identifier is passed in or a write open() -in file or a ‘w‘ ‘wb‘ binary file is written

With open ("Test.txt", ' W ') as F:    f.write ("Hello World")--------------------------------------$ cat test.txt$ Hello World

You can write to write() the file repeatedly, but be sure to call f.close() to close the file. When we write a file, the operating system often does not immediately write the data to disk, but put it into memory cache, idle time and then slowly write, if you want to let the content write in real time, you can use Flush (). Only when the method is invoked close() does the operating system guarantee that all data that is not written is written to disk. The consequence of forgetting the call is that the close() data may have only been written to the disk, and the remainder has been lost. So, it is safe to use with statements.

3. File Operation identifiers

R opens the file in read-only mode. The pointer to the file will be placed at the beginning of the file. This is the default mode.
r+ Open the file as read-write. The file pointer will be placed at the beginning of the file.
W opens the file in write-only mode. Overwrite the file if it already exists. If the file does not exist, create a new file.
w+ Open the file as read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
A opens the file in Append mode. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.
A + opens the file in read-write mode. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write.

4. File Operation other tips

Tell (): Print the current position

f = open ("Test", ' R ') print (F.read ()) print (F.tell ()) F.close () >>this is a >>10 

The Seek (offset [, from]) method changes the position of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes.

If from is set to 0, this means that the beginning of the file is used as the reference location for moving bytes. If set to 1, the current position is used as the reference location. If it is set to 2, then the end of the file will be used as the reference location.

f = open ("Test", ' R ') F.seek (10,0) print (F.read ()) F.close ()
>>file>>life is Short>>use python

  

Two. Character encoding and transcoding

Reference article:

http://www.cnblogs.com/yuanchenqi/articles/5956943.html

Three. Function basics

A function is to encapsulate a set of statements by a name (function name), and to execute this function, simply call the name of its functions

Characteristics:

1. Reduce duplication of code

2. Increased scalability

3. Convenient for future maintenance

1. Define a function   

def hello ():                  #定义一个函数名为hello的函数    print ("Hello world\n") hello ()                       #调用hello () function >>hello World        

  2. Function parameters

Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

Not to be finished ...

Python Learning Note: basic Day03

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.