A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
Name: is mandatory option, mode and buffer are optional
#假设文件不在. The following error is reported:
file Mode>>> 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 '
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.
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,
#对于非空文件: When the W method is supplied, the contents of the file are overwritten>>> f = open (' Somefile.txt ', ' W ') >>> f.write (' Hello, ') >>> f.write (' world! ') >>> f.close () #somefile. txt file contents hello,world!
example of a simple read:>>> 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.
Pipe Output>>> 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 ()
$ 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!
Output Result:#somescript. Pyimport Systext = sys.stdin.read () words = Text.split () print "Word Count:", Len (words)
Random interview:# Cat Somefile.txt | Python Somescript.pyword count:11
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
read-write line:>>> 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
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
Close File#UNIX >>> import os>>> os.linesep ' \ n ' #WINDOWS >>> import os>>> os.linesep ' \ r \ n '
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
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.# Open your file heretry: # Write data to your filefinally: file.close ()
use the basic method :
Welcome to this file
There is nothing here except
This stupid haiku
Reads the specified character first
Second, read all rows>>> f = open (R ' d:\Learn\Python\somefile.txt ') >>> f.read (7) ' Welcome ' >>> f.read (4) ' to ' > >> F.close ()
then read the line>>> f = open (R ' D:\Learn\Python\somefile.txt ', ' R ') >>> print f.read () Welcome to this filethere is Nothing here exceptthis stupid haiku
read all the lines again:>>> 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
The following is a write file>>> Import pprint>>> pprint.pprint (open (' Somefile.txt '). ReadLines ()) [' Welcome to this file\n ', ' There is nothing here except\n ', ' This stupid haiku ']
and finally the Writelines .>>> 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
iterate over the contents of a file>>> f = open (R ' somefile.txt ') >>> lines = F.readlines () >>> f.close () >>> lines = " 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
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
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 ') char = F.read (1) while char: process ( char) char = f.read (1) f.close ()
Note: This is better than the above, avoiding repeated code.def process (string): print ' processing ... ', STRINGF = open (' Somefile.txt ') while True: char = f.read (1) if Not char: break process (char) f.close ()
Action by row
Read all contentf = open (filename) while True: line = F.readline () If the line: Break Process (line) F.close ()
Assume that the file is not very large and can be processed using read () or readlines () read as a string.
#用readlines来迭代行f = open (R ' D:\Work\Python\somefile.txt ') for Char in F.read (): process (char) f.close ()
using Fileinput to implement lazy line iterationsf = open (R ' D:\Work\Python\somefile.txt ', ' r ') for line in F.readlines (): process (line) F.close ()
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.
file iteratorsImport Fileinputdef Process (string): print ' processing ... ', stringfor line in Fileinput.input (' Somefile.txt '): Process (line)
#Python中文件是能够迭代的, it's very elegant to write.
#假设希望Python来完毕关闭的动作, iterate over the file without using a variable to store the variablef = open (' somefile.txt ') for line in F: print line,f.close ()
Sys.stdin is also capable of iterative, simple code such as the following:For on open (' Somefile.txt '): print Line,
#能够对文件迭代器执行和普通迭代器同样的操作. For example, convert them to a list of strings, which results in the same effect as using ReadLines. Examples include 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!
Note:>>> 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 '
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
<< Basic Python Tutorials >> Learning Notes | 11th Chapter | Files and footage
Start building with 50+ products and up to 12 months usage for Elastic Compute Service