[Python learning] topic four. Documentation Basics

Source: Internet
Author: User

The basics of functions, statements, and strings are described earlier in this article, which focuses on the basics of files (very similar to other languages).

I. Basic operation of the file

a file is a collection of data stored on an external medium, such as a disk. The procedure for the file is:
Open file (read \ Write), read-write file (read\readline\readlines\write\writelines), close file
1. Open File
The Call function open opens the file with the function format:
File_obj=open (filename[, mode[, Buffering]) returns a File object
-filename file name (unique mandatory parameter)
• Original String R ' C:\temp\test.txt '
• Transfer string ' c:\\temp\\test.txt '
-mode File mode
• R Read mode
• W Write mode
a append mode (write at last)
+ read/write mode (no files are created and can be added to other modes for use)
・the binary mode (can be added to other modes for use)
-buffering buffer (optional parameter)
                                                 
• Parameter = 0 or false input/output I/O is unbuffered and all read and write operations are for the hard disk
• Parameter = 1 or true input/output I/O is buffered, memory replaces hard disk
• The parameter >1 number represents the size of the buffer, in bytes.-1 or negative indicates the default buffer size is used
Note: When working with binary files such as sound clips or images using ' B ' binary mode, you can ' RB ' read a binary file.
2. Close the file

It should be remembered to close the file using the Close method, because Python might cache (for efficiency, temporarily storing the data somewhere) and write to the data, and if the program suddenly crashes, the data is not written to the file at all, and is closed after the file is used for security purposes. If you want to make sure that the file is closed, You should use the Try/finally statement and call the Close method in the finally clause. such as:
#Open your file
Try
#Write data to your file
Finally
File.close ()

3. Read and Write files
calling the function write method writes data to a file whose function format is:
the File_obj.write (string) argument string is appended to the existing part of the file
File_obj.writelines (sequence_of_strings) only passes one parameter, list [] tuple () dictionary {}
Note: The order of the strings in the practical dictionary occurs randomly.

#使用write () Write File File_obj=open (' Test.txt ', ' W ') str1= ' hello\n ' str2= ' world\n ' str3= ' python ' file_obj.write (str1) file_ Obj.write (STR2) file_obj.write (STR3) file_obj.close () #使用writelines () write File File_obj=open (' Test.txt ', ' W ') str1= ' hello\ N ' str2= ' world\n ' str3= ' python ' file_obj.writelines ([STR1,STR2,STR3]) file_obj.close () #输出 Local Test.txt file Hellowordpython

The call function reads the data with the function format: Var=file_obj.read (), where read reads all, returns String;readline reads a row, returns String;readlines reads all the rows of the file, returns a List of String. Example:

#使用readprint ' Use the read ' File_obj=open (' test.txt ', ' R ') s=file_obj.read () print sfile_obj.close# using Readlineprint ' uses The ReadLine ' File_obj=open (' test.txt ', ' R ') Line1=file_obj.readline () Line1=line1.rstrip (' \ n ') print ' L1 ', line1line2 =file_obj.readline () Line2=line2.rstrip (' \ n ') print ' L2 ', Line2line3=file_obj.readline () line3=line3.rstrip (' \ n ') print ' L3 ', line3file_obj.close# using Readlinesprint ' Use the ReadLines ' File_obj=open (' test.txt ', ' R ') li=file_ Obj.readlines () Print Lifile_obj.close

The output reads as follows:

Use the Readhelloworldpythonuse the Readlinel1  hellol2  worldl3  pythonuse the readlines[' hello\n ', ' world\ n ', ' Python ')

It can be found that the result returned when using the ReadLine () function is the ' hello\n ' string, which requires the use of Rstrip to remove ' \ n ', otherwise the print output will have a total blank line. It is convenient to write to the file using formatted write, such as s= "xxx%dyyy%s\n"% ( , ' csdn ').

#格式化写入fd =open (' Format.txt ', ' W ') head= "%-8s%-10s%-10s\n"% (' Id ', ' Name ', ' Record ') fd.write (head) item1= "%-8d%-10s%- 10.2f\n "% (10001, ' Eastmount ', 78.9) fd.write (item1) item2="%-8d%-10s%-10.2f\n "% (10002, ' CSDN ', 89.1234) Fd.write ( ITEM2) fd.close () #输出Id Name Record 10001 eastmount 78.90 10002 CSDN 89.12
two. Documents and Loops

The basic operation and usage of the file are described earlier, but the file operations are usually associated with loops, which describe the while loop and the For loop implementation file operation. The code is as follows:

#使用while循环fr =open (' Test.txt ', ' R ') Str=fr.readline () Str=str.rstrip (' \ n ') while str!= "":    print str    str= Fr.readline ()    str=str.rstrip (' \ n ') Else:    print ' End while ' fr.close# uses for loop rfile=open (' Test.txt ', ' R ') for s In Rfile:    s=s.rstrip (' \ n ')    print sprint ' End for ' rfile.close ()

where for call iterator iterator, an iterator provides a way to sequentially access individual elements in an aggregate object, which is equivalent to an iterator that obtains an object through the ITER function, and then passes the next function (which does not require any parameters when the method is called) Gets the next value. For can traverse iterator_obj including List\string\tuple\dict\file. Such as:
s= ' Www.csdn.net '
Si=iter (s) #生成迭代器
Print Si.next () #调用next依次获取元素, Stopiteration exception is thrown when the last iterator does not return a value

three. Summary

This article focuses on the basics of Python files, including opening, reading and writing of files, closing operations, and knowledge of using loops to read and write files and iterators. Hope to help you, if there are errors or shortcomings, also please Haihan!
(by:eastmount 2014-9-28 Noon 11 o'clock Original CSDN http://blog.csdn.net/eastmount/
)
references:
1.51CTO College Zhipu Education python video
http://edu.51cto.com/course/course_id-581.html
2. "Basic Python Tutorial (2nd edition)" Magnus Lie hetland[]

[Python learning] topic four. Documentation Basics

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.