& Lt; Python basic tutorial & gt; learning notes | Chapter 2 | files and materials,

Source: Internet
Author: User
Tags pprint

<Python basic tutorial> learning notes | Chapter 4 | files and materials,

Open a file

Open (name [mode [, buffing])

Name: mandatory. mode and buffer are optional.

# If the file is not present, the following error is reported:

>>> f = open(r'D:\text.txt','r')Traceback (most recent call last):  File "<stdin>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'D:\\text.txt'
File Mode


NOTE:

1. The default mode. For example, open ('filename') is read mode.

2. r + indicates read/write.

3. If it is a binary or graphical file, the buffer mode must be used.

4. The normal w mode will overwrite the file content, but the mode will not.

5. rb can be used to read binary files.

6. Using the U parameter in the parameter mode, you can use the common line break support mode when opening a file. \ r, \ n \ r will be changed to \ n, instead of running the platform.

Buffer:

The third parameter. Optional.

0 or False: no buffer. All operations are directly performed on the hard disk.

1 Or True: there is a buffer, the memory replaces the hard disk, the speed is fast, only close, flush write to the hard disk synchronization.

> 1: indicates the buffer size.

-1: indicates the default buffer size.


Basic file Method

NOTE: class object is an object that supports some file methods, such as the file method. The two most important methods are the read and write methods. and urllib. urlopen returns objects. Supported methods include read, readline, and readlines.

Three standard streams

Sys. stdin: standard input stream, which can be linked to standard output of other programs by input or pipeline to provide text

Sys. stdout: place the data written by input and raw_input, which can be displayed on the screen or through | connect to the standard input of other programs

Sys. stderr: Error message. For example, stack tracing is written to sys. stderr.


Read and Write

The most important capability is to provide read/write

# For empty files: When writing is provided, it will be appended at the end of the string,

>>> F = open('somefile.txt ', 'w') >>> f. write ('hello,') >>> f. write ('World! ') >>> F.close(f.#somefile.txt file content Hello, World!
# For non-empty files: If the w method is provided, the content in the file will be overwritten.

>>> F = open ('somefile', 'w') >>> f. write ('this is 1st line. \ n') >>> f. write ('this is 2nd line. ') >>> f.close(**somefile.txt file content This is 1st line. this is 2nd line.
Example of simple reading:

>>> F = open('somefile.txt ', 'R') >>> f. read (16) # first read 16 characters 'this is 1st line' >>> f. read () # The remaining content will be read, unless the seek is located at 0 and re-read '. \ nThis is 2nd line. '>>> f. close ()
MPs queue 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 is a dog!
Who are you?

Script list

#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 you are interested in

Seek (offset [, whence]). offset, offset, Whence Value

0: Start position

1: current location

2: End of the file

Simple Example:

>>> F = open('somefile.txt ', 'w') >>> f. write ('20140901') >>> 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) '34' >>> f. tell () 5L
Read/write rows:

Readline: Read rows, including line breaks

Readlines: Read all rows

Write: write a row. Note: There is no writeline method.

Writelines: write multiple rows

NOTE: How can I determine the end of different rows? OS. linesep

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

Always remember to close () to close the file:

1. For security reasons, prevent files from being crashed for some reason and data cannot be written.

2. For Data Synchronization considerations, close () will write data to the hard disk

3. for efficiency, some data in the memory can be cleared.

To ensure close () at the end of the program, try/finally

# Open your file heretry:    # Write data to your filefinally:    file.close()
NOTE: Generally, files are written to the hard disk after being close (). If you want to see the written content without executing the close () method, flush will be used.


Basic method:

Compile test somefile.txt

Welcome to this file

There is nothing here except T

This stupid haiku

First read the specified character

>>> f = open(r'd:\Learn\Python\somefile.txt')>>> f.read(7)'Welcome'>>> f.read(4)' to '>>> f.close()
Next, 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
Next, read the row.

>>> 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 is 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']
Below is the file writing

>>> F = open(r'somefile.txt ', 'w') >>> f. write ('this \ nis no \ nhaiku ')> f. after close () runs the file, the content is as follows: thisis nohaiku
The last is 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. after close () is run, the file content is as follows: this isn't ahaiku
Iterate the File Content

Basic methods include: read, readline, readlines, and xreadline and file iterator.

In the following example, the virtual function process () is used to process each character or each line.

Def process (string ):

Print 'processing', string

A more useful implementation is to store data, computation, and value in the data structure. Use the re module to replace the mode or add a row number. If you want to implement the above functions,

The filename variable is set to the actual file name.


Byte processing

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 Code as follows:

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.

Operate by row

f = open(filename)while True:    line = f.readline()    if not line:        break    process(line)f.close()
Read all content

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

# Use read to iterate each string

f = open(r'D:\Work\Python\somefile.txt')for char in f.read():    process(char)f.close()
# Use readlines to iterate rows

f = open(r'D:\Work\Python\somefile.txt','r')for line in f.readlines():    process(line)f.close()
Implement lazy row iteration using fileinput

When You Need To iterate a large file, readlines will occupy too much memory. In this case, the while loop and readline methods can be used instead.

import fileinputdef process(string):    print 'Processing...', stringfor line in fileinput.input('somefile.txt'):    process(line)
File iterator

# Python files can be iterated and written elegantly.

f = open('somefile.txt')for line in f:    print line,f.close()
# If you want Python to complete the close operation, iterate the file without using variables to store Variables

# Code can be streamlined

for line in open('somefile.txt'):    print line,
Sys. stdin can also be iterated. The simple code is as follows:

Import sysfor line in sys. stdin: print line. Run the following command: D: \ Work \ Python> python file. py # input the following two lines: Hello, World! Hello, Jerry! ^ Z # after pressing CTRL + Z, the input content will display Hello, World! Hello, Jerry!
# You can perform the same operations on the file iterator as the normal iterator. For example, convert them to a string list, which achieves the same effect as using readlines. For 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. Sequence-based unpacking is very useful.

2. You do not need to close () when reading a file ()

------

New functions in this Chapter

File (name [, mode [, buffering]) open a file and return a file object

Open (name [, mode [, buffering]) file alias; when opening a file, use open instead of file




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.