Python Notes 4 --- File Operations

General procedure and operation code files

Logical file operation is

  1. 1 Open the file
  2. 2 Action File
  3. 3 close the file

Corresponding to the code is:

file = open('filename')
f=file.read()或者类似操作,通过句柄对象来操作文件***
file.close  

Open the file open function

Open (File, mode = 'R & lt', Buffering = None, encoding = None, errors = None, NEWLINE = None, closefd = True)
File path and file name strings, you can also be used relative to an absolute path
mode requires detailed explanation, the default is read-only + text mode.
Buffering related to how the cache, as well as the size of the cache block, no need to know.
encoding is encoded file read and write files using decoding mode. Note that this is not an internal coding of python , but encoding the file itself.
errors refers to coding errors when a prompt string.
nEWLINE refers to control what wrap takes effect only in text mode. If set to None, then using a common mode, \ n, \ r, \ r \ n can wrap, three things will be converted to \ n returns the results to the open function. If set to ", \ n \ r \ r \ n will not be converted into \ n, all other . None provided as to when the file is written, arranged None, line breaks were converted into the system default newline If set to 'or' \ n ', is not converted;. If set to another character, the newline is replaced with the character. this is done to Maintaining platform compatibility, wrap windows platform is \ r \ n, but if you read the time remain the same cause misunderstanding. But \ r \ n real, in the method used to move the file pointer in, pay attention to the file at the end of a one-time moving the two.
closefd default is True, if closefd is False, then close the file, the underlying file descriptor remains open. If the given file name does not work in this case must be True.
obtain a file open function objects (handles) after performing the operation can then be assigned to a variable.

Operation of the document

The method of file objects:
File.read () disposable reading all file content, if a text mode, returns a String object if it is a binary file, if the object returns a bytes read (for) traverse operations take. things, then, file pointer of the file may be added depending on the operating parameter value change position, indicates the reading of N characters.
file.readable () determines whether the object is readable, such as opening a write-only mode, the result is False
FILE.readline () when one reads the contents of one row, the end of the line includes a line break. and the file pointer to the start of the next line, the function is executed again, returns the next line.
file.readlines () to read all of the rows, each row consisting of a list is returned.

file.writeable () is writable
file.write () the contents of the written documents, the argument is a string. return wrote a few characters.
file.writelines (), pass a parameter list containing the elements of each string, will each element written into it.

Close the file

After completing the operation, the need to close the two things, first, to close the file handle from the operating system to get the second is assigned to close the file object variable.
Python generally automatic operation of the second term, so be sure to take file.close ( ) notify the operating system shut down.
If you feel too much trouble to manually shut down, can be used with context management, content with other statements as a code block .with can open two files at the same time,

with open('a.txt','w') as f1,open('b.txt','r') as f2:
    f1.read()
    f2.read()
    ...

Open the file mode

r Read-only, open when not modify the contents of the file, can not save the file. Read series of methods can be used
w Write-only, unreadable .w mode when open, if the same name file exists, the file will be empty, and if not, it will create a new file. Write series of methods can be used
a Append mode. Able to write, to write the append mode unreadable at the end of the .a file
r+ On the basis of the read and write functions r .r + opening the file pointer in the start position.
w+ First overwrite the original file of the same features, read and write
a+ Read and write, time to open the file pointer at the end of the file.
b = Binary file for opening files other than text files, need to use mode, byte mode and the fundamental mode can be used in combination, such as rb, wb, ab

File byte mode operation

Before the operation is a text file. Files outside of a text file, you need to use byte mode and manipulate text files is no different, the time to write to pay attention to the type of data bytes must be written.
Require the use of built-in functions bytes (content , coding) to replace the contents of some files encoded byte. Alternatively, if desired to write cross-platform program, generally used with .decode byte pattern or string .encode method, because of different operating systems, are the underlying If binary mode is dependent on the coding system, the various problems that may arise.
binary -> string decoding
string -> binary encoding
remember encoding a book?

Other methods of file

Open the file does not find what coding, they can try to encode designated as latin-1, it will be as much of a reserved character.

file.closed() Whether the file has been closed
file.flush() The memory data to the hard disk brush
file.name File name, is a property, not a method
file.seek(int,mode = 0) Three modes: a file pointer is moved to the specified, int index .0 pattern here is for the first byte of the index file is 0, int represents the relative position of the last few moves to the corresponding index mode .1 the need to open the file from the end of the file .2 mode indicates the beginning seek to b mode, this time int should be negative.
file.tell() File pointer position, where the pointer is in accordance with statistical line break within a byte of the system is actually .windows \ r \ n, two count bytes.
file.truncate(int) Intercepting a file belonging to a write operation. Preserve the contents of the specified byte length. Int here is not the index, it is the normal length.

The method may be used to seek tell move the file pointer operation.
Small TIP: for i in file: this () better than for i in file.readlines, not all the lines are read into the first memory, as the former image generator, to once only to once
something is later written document handling utilities frequently used, the need for repeated practice.

Guess you like

Origin www.cnblogs.com/bmxm/p/11927719.html