Basic Python Tutorial Chapter 11th: File and Stream Learning notes

Source: Internet
Author: User

This article is reproduced in the following sections:

Http://www.runoob.com/python/python-files-io.html

Http://docs.pythontab.com/python/python2.7/inputoutput.html#tut-files

Open File:

You must first open a file with the Python built-in open () function, create a Document object, and the associated helper method can call it for read and write.
Grammar:

Object= Open([, access_mode] [, buffering])     

The details of each parameter are as follows:

The File_name:file_name variable is a string value that contains the name of the file you want to access.
Access_mode:access_mode determines the mode of opening the file: read-only, write, append, etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R).
Buffering: If the value of buffering is set to 0, there is no deposit. If the value of buffering is 1, the row is stored when the file is accessed. If you set the value of buffering to an integer greater than 1, it indicates that this is the buffer size of the storage area. If a negative value is taken, the buffer size of the storage area is the system default.

Full list of open files in different modes:

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.
RB opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+ open a file for read-write. The file pointer will be placed at the beginning of the file.
rb+ opens a file in binary format for read-write. The file pointer will be placed at the beginning of the file.
W opens a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.
WB opens a file in binary format for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.
w+ open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
wb+ opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
A opens a file for appending. 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.
AB opens a file in binary format for appending. 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 a file for read and write. 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.
ab+ opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write.

Properties of the File object:

After a file is opened, you have a files object that you can get various information about the file.
The following is a list of all properties related to the file object:
File.closed returns True if the file has been closed, otherwise false is returned.
File.mode returns the access mode of the file being opened.
File.name returns the name of the file.
File.softspace if the print output must be followed by a space character, false is returned. Otherwise, returns True.

# Open file f = open ("1.txt""r+")#  File name print  f.name# file is closed print  f.closed # mode of File open Print F.mode

1.txt
False
r+

To close a file:

The close () method of the file object flushes any information that has not yet been written in the buffer and closes the file, which can no longer be written.
When a reference to a file object is re-assigned to another file, Python closes the previous file. Closing a file with the close () method is a good habit.

Write file:

The write () method writes any string to an open file. It is important to note that the Python string can be binary data, not just text.
The Write () method does not add a line break (' \ n ') at the end of the string

Read the file:

The Read () method reads a string from an open file. It is important to note that the Python string can be binary data, not just text.
Grammar:
Fileobject.read ([Count])
Here, the parameter being passed is the count of bytes to read from the open file. The method reads in from the beginning of the file, and if it does not pass in count, it tries to read as much more content as possible, most likely until the end of the file.

File Location:

The tell () method tells you the current position within the file, in other words, the next read and write will occur after so many bytes at the beginning of the file
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.

#Open Filef = open ("1.txt","r+")#Write file ContentsF.write ("hello\r\n") F.write ("Hello")#gets the current file pointer positionPrintF.tell ()#move file pointer to file headerf.seek (0)#gets the current file pointer positionPrintF.tell ()#Read File contentsPrintF.read () f.seek (0)PrintF.read (3)#Close FileF.close ()

13
0
Hello
Hello
Hel

Read-Write line:

File.readline: Reads a single line (starting at the current position until a newline character appears), does not use any parameters (one line is read and returned), or uses a nonnegative integer as the maximum value that the ReadLine can read.

File.writelines: Pass it to a list of strings (actually any sequence or iteration of an object), which writes all the strings to the file. Note that the program does not add new lines and needs to be added yourself.

Submit cached data to file:

With open ("1.txt""r+") as f:    = 0      while True:        f.write ("zzzzzzzz")        #  Submit cached data to file         f.flush ()        + = 1        if i >:             break

Recommended wording:

Try :     = Open ("1.txt""r+")        print  F.readline ()finally:    f.close ()

The second recommended wording:

# The with statement can open a file and assign it to a variable somefile, and then write the data to a file in the body of the statement.  # files are automatically closed after the statement ends, even if the exception causes the end. with open ("1.txt") as Somefile:    print somefile.readline ()

Iterate over the contents of a file: In addition to reading the contents of the file using the Read method above, there are other ways to iterate over the contents of the file.

 with open ( 1.txt   ", "  r+   ) as F:  #   Use read to iterate through each character  for  char in   F.read ():  print   char  
With open ("1.txt""r+") as F:    #  Use ReadLines to iterate the row for in      f.readlines ()        :print Line

ReadLines consumes too much memory when it is necessary to do a row iteration of a very large file. This time you can use the while loop and the ReadLine method instead, and you can use a for loop with a method called Lazy line iteration:

Import Fileinput # The reason why it's lazy is because it just reads the file part of the actual need  for  in Fileinput.input ("1.txt"):    Print Line

There is also a method of content iteration called a file iterator that, at the beginning of the Python2.2, the file object is iterative:

With open ("1.txt""R") as F:      F:        Print Line

Pickle module:

We can easily read and write the strings in the file. The value will be a little more trouble, because the read () method will only return a string, it should be passed into an int () such a method, you can convert the character ' 123 ' to the corresponding value 123. However, when you need to save more complex data types, such as lists, dictionaries, and instances of classes, things can get more complicated.

Fortunately, users do not have to write and debug their own code that holds complex data types. Python provides a standard module called Pickle. This is an amazing module that can almost put any Python object (even some Python code snippets!). ) is expressed as a string, and this process is called encapsulation (pickling). The reconstructed object is called a tamper-unpickling from a string expression. Objects in the encapsulated state can be stored in files or objects, or transferred between remote machines over a network.

If you have an object x, a file object F that opens in write mode, the simplest way to encapsulate an object is just one line of code:

Pickle.dump (x, F)

If f is a file object opened in read mode, you can reload the object:

x = Pickle.load (f)

(If you don't want to write the encapsulated data to a file, there are some other changes available here.) For a complete pickle documentation, see the Python Library Reference manual).

Pickle is a standard method for storing Python objects for later invocation by other programs or themselves. This set of techniques is provided by a persistent object (persistent. Because Pickle is widely used, many Python extension authors pay great attention to whether new data types like matrices are suitable for encapsulation and unpacking.

ImportPicklel= [1, 2, 3, 4]d= {"name":"Zhangsan"," Age":" A","Phone":" the"}with Open ("1.txt","r+") as F:#Write ListPickle.dump (L, F) f.write ("\ r \ n")    #Write DictionaryPickle.dump (d, F)" "structure after writing to file: (lp0i1ai2ai3ai4a. ( dp0s ' phone ' p1s ' p2ss ' age ' p3s ' of ' p4ss ' name ' p5s ' Zhangsan ' p6s." "With Open ("1.txt","R") as F:#reading list DataL1 =pickle.load (f) f.readline ()#Reading Dictionary dataD1 =pickle.load (f)PrintL1PrintD1

[1, 2, 3, 4]
{' phone ': ' + ', ' age ': ' + ', ' name ': ' Zhangsan '}

Basic Python Tutorial Chapter 11th: File and Stream Learning notes

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.