Python file operations: Read and write files

Source: Internet
Author: User
Tags truncated

The Open function: Before the file read and write, you need to open the file, get the file handle Note: Open () file () use open () as far as possible, Python3 does not support file () 1, open (file_name[,access_mode][, Buffering]) (1) parameter description file_name: A string value that contains the path and file name of the file you want to access. Try to use absolute path Access_mode: The way to open a file: This parameter is non-mandatory, the default file access mode is read-only (R) r, read-only W: Write will empty the contents of the file a: Append, in the original content to continue to write buffering: Write to the cache first if the value of buffering is set to 0, there is no deposit, and if the value is 1, the row is cached when the file is accessed, and if the value bit is greater than 1, this is the buffer size of the storage area, and if negative, the buffer size of the storage area is the system default. This parameter is also non-mandatory. (2) Return value This statement indicates that the returned file_object is a pointer to a file (a file object) file handle. When a nonexistent file is opened in read-only mode (R), the IOError exception is reported (the file does not exist), but if a nonexistent file is opened in write or append mode (w/a/a+), the file is created by default, but if there is a directory in the path that does not exist, the ioerror exception is reported   Create a file: Fp=open (' D:\\tmp\\01.txt ', W)  2, mode file operation mode r,w,ar+ readable writable w+: Open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. A +: Opens a file for read-write. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write.  RB WB AB Read-write binary  3, the file handle obtained through open can be used for other operations on the file (1) fp.closed determine if the file has been closed. Returns true if the file has been closed, otherwise returns False (2) Fp.mode output read-write mode. Returns the access mode of the file being opened. (3) Fp.name: Returns the name of the file. (4) Fp.softspace If the print output is followed by a space character, false does not print, true prints. (5) Fp.close () flushes any information that is not yet written in the buffer and closes the file, which can no longer be written. (6) Flush () persist the contents of the buffer to write the cache in the disk, the system will automatically call FlusH () method. When flush is called: How much length of data is written, or how long it takes to persist if no flush (), persistent content is lost (7) Next () # for I in fp:# print I use a file such as for...in file to iterate through the statement, is to invoke the next () function to implement. File handle is an iterator???  fp=open (FileName, ' R ')  print Fp.next () print fp.next () print Fp.fileno () determines which file handle is the current operation Numberfp.close ()   (8) clipping file truncate ([size]) is used to truncate a file, and if an optional parameter size is specified, the truncated file is a size character. If size is not specified, it is truncated from the current position, and all characters after the size are deleted after truncation. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add. fp= ' E:\\tmp\\03.txt '  f1=open (FP, ' r+ ') line=f1.readline () print line f1.truncate () print F1.tell () f1.close ()   Second, read and write to the file 1, normal read and write operation (1) Read ([size]) Size: The length of the read, in bytes. If you do not specify a parameter, the entire content is read once, returned as a string, and there is a "\ n" symbol at the end of each line.   (2), ReadLine ([size]) reads one line at a time, if given a size, it is possible to return only a portion of a line, returned as a string, and a newline character "\ n" at the end. After reading a line, the file action tag moves to the beginning of the next line. Returned is the string   (3), readlines ([size]) (3.1) parameter size: Specifies a small number that will not take effect, python default 8k buffer size, need to be greater than 8k effective read the entire contents of the file, The inside of this function is implemented by looping through calls to ReadLine () (3.2) The return value returns the list format, each row is an element of the list, and ends with a line break "\ n"   (4), writelines (seq) Seq: Writes the contents of the SEQ (sequence) to the file (multiline write-once). Also does not automatically add line breaks。 Note: The contents of the sequence must also be string-type data to successfully write to the file.   (5), write (str) writes STR to the file, the default is no newline character, so if you want to change the line, you have to manually add a newline character ' \ n '.  2, using the Linecache module to read the file import Linecache allows any row to be fetched from any file, and is optimized with caching, and it is common to read multiple lines from a single file. (1) linecache.getlines (Filename,lineno) Gets the Lineno line from the file named filename. This function never throws an exception-it will return when an error occurs (the newline will be included in the found row). If the file is not found, the function will be searched in Sys.path. (2) linecache.getlines (filename) Returns a list of all the contents from a file named filename, output as a list format, one element in the file per behavior list, and a linenum-1 Store (3) Linecache.clearcache () clears the cache for the position of the element in the list, and if you no longer need the row (4) Linecache.checkcache ([filename]) previously obtained from Getline (), check the validity of the cache. If the files in the cache have changed on the hard disk, and you need to update the version, use this function. If you omit filename, all entries in the cache are checked. (5) Linecache.updatecache (filename) updates the cache with file name filename. If the filename file is updated, use this function to update the list returned by linecache.getlines (filename).   Another: After reading the file you do not need to use the file cache when you need to clean up the cache at the end, so that Linecache.clearcache () clean up the cache and release the cache. This module uses memory to cache the contents of your files, so you need to consume memory, open file size and open speed and your memory size has a relationship. Print odd line files: fp= ' E:\\tmp\\05.txt ' List1=linecache.getlines (FP) for I in List1[::2]:p rint i 3, Pickle modules and Cpickle modules read and write to the entire file (1), pickle module (Python provides a standard module) List contents persist in memory use it you can store any PYT in a fileHon Object, and then you can take it out intact. This is called persistent storage object (serialization) (2), Cpickle list, and file content conversion its functionality is identical to the Pickle module, except that it is written in C and therefore much faster (1000 times times faster than pickle) and recommended. Import Cpickle as Pp.dump (LIST,FP) Saves the list contents to memory in a file (this file has a Cpickle-specific format) FP: Open file handle, such as: Fp=open (' d:\\tmp\\ Test1.txt ', ' WB ') list=p.load (FP) save content previously stored in the file to list    third, location to read files 1, tell () Returns the location of the current action file read to a Chinese: 3 bytes under Windows ' \ r \ n ' (newline character) accounted for two bytes, Linux under \ n mac under \r.2, Seek (Offset[,from]) move the cursor to where you want to go from:, default is 0, 2: The offset is calculated from the end, 1: from the current position as the standard position offset: The total distance moved, can be positive, can be negative  

Python file operations: Read and write files

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.