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

Source: Internet
Author: User
Tags stack trace 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, for example 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 parameter in the parameter mode, can use the common line break support mode when opening the file, regardless of the \r,\n\r, it will be changed to \ n instead of running platform.

Buffer:

A third parameter, optional

0 or false: No buffering, all operations are directed to the hard drive

1 or true: There is buffering, memory instead of hard disk, fast, only close,flush to write HDD sync.

> 1: Indicates the size of the buffer

-1: Indicates the default buffer size


Basic File Method

Note: The class file object is an object that supports a number of files, such as the file method, the most important two methods, and 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 input,raw_input written data, which can be displayed on the screen or 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

#对空文件来说: When a write is provided, it 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.
examples of simple reads:

>>> f = open (' Somefile.txt ', ' R ') >>> F.read #先读取16个字符 ' This is 1st line ' >>> f.read ()  # Will read the remainder unless seek locates to 0 and re-reads '. \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 Access:

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 example:

>>> 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 lines, including newline characters

ReadLines: Read all rows

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

Writelines: Write Multiple lines

Note: How can I tell 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 collapsing for some reason, write data

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 written to the hard disk after close (), and if you want to see what is written without executing the close () method, flush will come 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 ()
next Read all the 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 rows again:

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

>>> f = open (R ' Somefile.txt ', ' W ') >>> f.write (' This\nis no\nhaiku ') >>> F.close () after running 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 running, the file contents are as follows: This isn ' t ahaiku
iterate over the contents of a file

Basic methods such as: Read,readline,readlines, and xreadline and file iterators

The following examples all use the virtual function process (), which represents each character or line of processing

def process (string):

print ' processing ', string

A more useful implementation is to store data, calculations, and values in a structure. Replace the mode with the RE module or add the line number. If 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 often a bad thing, and laziness is a virtue. Rewrite the following code:

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 duplication of code.

Action by row

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

If the file is not very large, you can use Read (), or readlines () to read the content as a string to handle.

#用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 consumes too much memory. This time you can use the while loop and the ReadLine method instead.

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

#Python中文件是可以迭代的, it's 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 can also be iterated, with the following simple code:

Import sysfor line in Sys.stdin:    print lines, run result: D:\work\python>python file.py# Enter the following two rows hello,world! Hello,jerry!^z      #按下CTRL The +z key, the input content is displayed hello,world! hello,jerry!
#可以对文件迭代器执行和普通迭代器相同的操作. For example, convert them to a list of strings, which achieves the same effect as using ReadLines. The following example:

>>> 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, you can not close ()

------

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

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

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.