<< Basic Python Tutorials >> Learning Notes | 11th Chapter | Files and footage

Source: Internet
Author: User
Tags readline stack trace stdin pprint

Open File

Open (Name[mode[,buffing])

Name: is mandatory option, mode and buffer are optional

#假设文件不在. The following error is reported:

>>> f = open (R ' D:\text.txt ', ' R ') Traceback (most recent):  File "<stdin>", line 1, in <modul E>ioerror: [Errno 2] No such file or directory: ' D:\\text.txt '
file Mode


Note:

1. The default way, say open (' filename ') is read mode

2. r+, which means read/write

3. If it is a binary file or a graphics file, you must use buffer mode

4. Normal W mode overwrites the contents of the file, and a mode does not.

5. RB can be used to read binary files.

6, using the U-parameters in the parameter mode, you can use the Universal line feed support mode when opening the file, regardless of the \r,\n\r, it will be changed to \ n. Without considering the execution of the platform.

Buffer:

The third number of parameters. Options available

0 or false: no buffering. All operations are directed to the hard drive

1 or true: There is buffering, the memory replaces the hard disk, the speed is fast, only has the Close,flush to write the hard disk synchronization.

> 1: Indicates the size of the buffer

-1: Indicates the default buffer size


Basic File Method

Note: Class file objects are objects that support methods of some files, such as the file method. The most important two methods, the Read,write method. There are also urllib.urlopen return objects, and the methods they support are: Read,readline,readlines

Three standard streams

Sys.stdin: Standard input stream, which can be used to link the standard output of other programs to text by entering or using a pipe

Sys.stdout: Place data written by Input,raw_input, can be displayed on the screen, or can be connected to standard input from other programs

Sys.stderr: Error message, such as stack trace is written to Sys.stderr.


Read and Write

The most important ability is to provide read and write

#对空文件来说: Provides write time. is appended at the end of the string,

>>> f = open (' Somefile.txt ', ' W ') >>> f.write (' Hello, ') >>> f.write (' world! ') >>> f.close () #somefile. txt file contents hello,world!
#对于非空文件: When the W method is supplied, the contents of the file are overwritten

>>> f = open (' Somefile ', ' W ') >>> f.write (' This was 1st line.\n ') >>> f.write (' This is 2nd line. ') >>> f.close () #somefile. txt file contents This is 1st line. This is a 2nd line.
example of a simple read:

>>> f = open (' Somefile.txt ', ' R ') >>> F.read #先读取16个字符 ' This is 1st line ' >>> f.read ()  # Will read the remainder unless seek navigates to 0, again read '. \nthis is 2nd line. ' >>> F.close ()
Pipe Output

$ Cat Somefile.txt | Python somescript.py | Sort

A simple example: count the number of words in a text

$ cat Somefile.txt
This is a book!
That's a dog!
Who is?

Script Checklist

#somescript. Pyimport Systext  = sys.stdin.read ()  words = Text.split () print "Word Count:", Len (words)
Output Result:

# Cat Somefile.txt | Python Somescript.pyword count:11
Random interview:

Use Seek and tell to access the parts of your interest

Seek (Offset[,whence]). Offset, offsets, whence values

0: Start position

1: Current Position

2: End of File

Simple examples:

>>> f = open (' Somefile.txt ', ' W ') >>> f.write (' 01234567890123456789 ') >>> F.seek (5) >> > F.write (' hello,world! ') >>> f.close () >>> f = open (' somefile.txt ') >>> f.read () ' 01234hello,world!789 ' # Use tell to return the location of the current file >>> f = open (' somefile.txt ') >>> f.read (3) ' 012 ' >>> f.read (2) ' "" >> > F.tell () 5L
read-write line:

ReadLine: Read line, including line break

ReadLines: Read all rows

Write: Writing a line, note: There is no WriteLine method

Writelines: Write Multiple lines

Note: How do you infer what the different lines end up with? Os.linesep

#UNIX >>> import os>>> os.linesep ' \ n ' #WINDOWS >>> import os>>> os.linesep ' \ r \ n '
Close File

Always remember close () to close the file, for the purpose of doing so:

1. For security reasons, prevent files from crashing for some reason. No data to write into

2. For data synchronization considerations, close () to write data to the hard disk

3. For efficiency reasons, the data in memory can be emptied partially.

To ensure close () at the end of the program, it can be used in conjunction with try/finally

# Open your file heretry:    # Write data to your filefinally:    file.close ()
Note: The general file is not written to the hard disk after close (), assuming you do not want to run the close () method. And you can see what's written, flush comes in handy.


use the basic method :

#測试文本somefile. txt

Welcome to this file

There is nothing here except

This stupid haiku

Reads the specified character first

>>> f = open (R ' d:\Learn\Python\somefile.txt ') >>> f.read (7) ' Welcome ' >>> f.read (4) ' to ' > >> F.close ()
Second, read all rows

>>> f = open (R ' D:\Learn\Python\somefile.txt ', ' R ') >>> print f.read () Welcome to this filethere is Nothing here exceptthis stupid haiku
then read the line

>>> f.close () >>> f = open (R ' d:\Learn\Python\somefile.txt ') >>> for I in range (3): ...     . Print str (i) + ': ' + f.readline () ... 0:welcome to this file1:there are nothing here except2:this stupid haiku
read all the lines again:

>>> Import pprint>>> pprint.pprint (open (' Somefile.txt '). ReadLines ()) [' Welcome to this file\n ', ' There is nothing here except\n ', ' This stupid haiku ']
The following is a write file

>>> f = open (R ' Somefile.txt ', ' W ') >>> f.write (' This\nis no\nhaiku ') >>> f.close () after executing the file, The contents are as follows: Thisis Nohaiku
and finally the Writelines .

>>> f = open (R ' somefile.txt ') >>> lines = F.readlines () >>> f.close () >>> lines[1] = " isn ' t a\n ">>> f = open (' Somefile.txt ', ' W ') >>> f.writelines (lines) >>> f.close () after execution. The contents of the file are as follows: This isn ' t ahaiku
iterate over the contents of a file

The main methods are: Read,readline,readlines, as well as xreadline and file iterators.

The following example uses the virtual function process (), which represents each character or line of processing

def process (string):

print ' processing ', string

A more practical implementation would be to store data in a structure. Calculations and values.

Replace the mode with the RE module or add the line number. Assume that you want to implement the above functionality.

You should say that the filename variable is set to the actual file name.


Processing by byte

def process (string):    print ' processing ... ', STRINGF = open (' somefile.txt ') char = F.read (1) while char:    process ( char)    char = f.read (1) f.close ()
code reuse is usually a bad thing, and laziness is a virtue. Rewrite the following code for example:

def process (string):        print ' processing ... ', STRINGF = open (' Somefile.txt ') while True:        char = f.read (1)        if Not char:                break        process (char) f.close ()
Note: This is better than the above, avoiding repeated code.

Action by row

f = open (filename) while True: line    = F.readline ()    If the line: Break    Process (line) F.close ()
Read all content

Assume that the file is not very large and can be processed using read () or readlines () read as a string.

#用read来迭代每一个字符串

f = open (R ' D:\Work\Python\somefile.txt ') for Char in F.read ():    process (char) f.close ()
#用readlines来迭代行

f = open (R ' D:\Work\Python\somefile.txt ', ' r ') for line in F.readlines ():    process (line) F.close ()
using Fileinput to implement lazy line iterations

When you need to iterate over a large file. ReadLines will consume too much memory.

You can use the while loop and the ReadLine method to replace it at this time.

Import Fileinputdef Process (string):    print ' processing ... ', stringfor line in Fileinput.input (' Somefile.txt '):    Process (line)
file iterators

#Python中文件是能够迭代的, it's very elegant to write.

f = open (' somefile.txt ') for line in F:    print line,f.close ()
#假设希望Python来完毕关闭的动作, iterate over the file without using a variable to store the variable

#代码能够更加精简

For on open (' Somefile.txt '):    print Line,
Sys.stdin is also capable of iterative, simple code such as the following:

Import sysfor line in Sys.stdin:    print lines, execution result: D:\work\python>python file.py# Enter the following two rows hello,world! Hello,jerry!^z      #按下CTRL the +z key. Input content, display hello,world! hello,jerry!
#能够对文件迭代器执行和普通迭代器同样的操作. For example, convert them to a list of strings, which results in the same effect as using ReadLines. Examples include the following:

>>> f = open (' Somefile.txt ', ' W ') >>> f.write (' first line\n ') >>> f.write (' Second line\n ') >>> F.write (' third line\n ') >>> f.close () >>> lines = list (open (' Somefile.txt ')) >> > lines[' First line\n ', ' Second line\n ', ' third line\n ']>>> first,second,third = open (' Somefile.txt ') > >> first ' first line\n ' >>> second ' second line\n ' >>> third ' third line\n '
Note:

1. Use the sequence to do the unpacking operation is very useful

2. Read the file operation, can not close ()

Use of With statements

The With statement wraps a block of code using the so-called context manager. Agree that the context manager implements some setup and cleanup operations.

For example: Files can be used as context managers, and they can be turned off as part of the cleanup.

Note: In PYTHON2.5, you need to import the With statement using the From __future__ import with_statement

With open (' Test.txt ') as myfile: When    True: line        = Myfile.readline () If the line        : Break        Print Line , #假设这样写的话. There is no need to close the file.
------

New functions in this chapter

File (Name[,mode[,buffering]]) opens a document and returns a File object

Open (Name[,mode[,buffering]]) file alias; When opening files, use open instead of file

&lt;&lt; Basic Python Tutorials &gt;&gt; Learning Notes | 11th Chapter | Files and footage

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.