[Switch] PYTHON open/file operations,
[Note] although it is reprinted, it will be modified in the original article!
Open/File Operations
F = open ('/tmp/hello', 'w ')
# Open (path + file name, read/write mode)
# Read/write mode: r read-only, r + read/write, w new (will overwrite the original file), a append, B binary file. Common Mode
For example, 'rb', 'wb ', 'r + B', etc.
The read/write modes include:
The rU or Ua is opened in Read mode and supports common line breaks (PEP 278)
W open in write mode,
A is opened in append mode (starting from EOF and creating a file if necessary)
R + Enabled in read/write mode
W + is enabled in read/write mode (see w)
A + is enabled in read/write mode (see)
Rb is enabled in binary read mode.
Wb is enabled in binary write mode (see w)
AB is enabled in binary append mode (see)
Rb + is enabled in binary read/write mode (see r +)
Wb + is enabled in binary read/write mode (see w +)
AB + is enabled in binary read/write mode (see a +)
Note:
1. Use 'W'. If the file exists, clear the file and create it again,
2. Use the 'A' mode to append all the data to be written to the file to the end of the file, even if you use seek () to point to other parts of the file, if the file does not exist, will be created automatically.
F. if the read ([size]) size is not specified, the entire file is returned. If the file size is greater than twice the memory size, the problem occurs. f. read () returns "" (Null String) when reading the end of a file)
File. readline () returns a row
File. readline ([size]) is modified here to return a string of the specified number of bytes.
For example, if the internal content is 1.txt 1111111111122222222222 # The program is f = open('1.txt ', 'R') print f. readline (2) print f. readline (), the result is: 1122222222222
For line in f: print line # access through iterator
F. write ("hello \ n") # If you want to write data other than a string, convert it to a string first.
F. tell () returns an integer indicating the position of the pointer to the current file (that is, the number of bits to the file header ).
F. seek (offset, [start position])
Used to move file pointers
Offset: Unit: Bit, positive or negative
Start position: 0-file header, default value; 1-Current position; 2-file end
F. close () close the file
Code:
#! /Usr/bin/env python # Filename: using_file.py
Poem = ''' \ Programming is funWhen the work is doneif you wanna make your work also fun: use Python! ''' F=file('poem.txt ', 'w') # open for 'W' riting F. write (poem) # write text to file F. close () # close the file F=file('poem.txt ')
# If no mode is specified, 'R' ead mode is assumed by default While True: Line = f. readline () If len (line) = 0: # Zero length indicates EOF Break Print line, # Notice comma to avoid automatic newline added by Python F. close () # Close the file |
From: http://hi.baidu.com/zzfxz/blog/item/1c4d73cb4aa2c814bf09e613.html