Python file read/write operations

Source: Internet
Author: User

You can't remember the API. I used this when I wrote it last night, but I didn't remember it, So I simply sorted it out: the operations on files and folders (file operation functions) in python involve the OS module and the shutil module. Obtain the current working directory, that is, the directory path of the current Python script: OS. getcwd () returns all files and directory names in the specified directory: OS. the listdir () function is used to delete a file: OS. remove () delete multiple directories: OS. removedirs (r "c: \ python") checks whether the given path is a file: OS. path. isfile () checks whether the given path is a directory: OS. path. isdir () determines whether it is an absolute path: OS. path. isabs () checks whether the given path is actually stored: OS. path. exists () returns the directory name and file name of a path: OS. path. split () eg OS. path. split ('/home/swaroop/byte/code/poem.txt') Result: ('/home/swaroop/byte/Code', 'poem.txt') Separation Extension: OS. path. splitext () Obtain the path: OS. path. get the file name: OS. path. basename () Run shell command: OS. system () reads and sets the environment variable: OS. getenv () and OS. putenv () indicates the row Terminator used by the current platform: OS. linesep Windows uses '\ r \ n', Linux uses' \ n', and Mac uses '\ R' to indicate the platform you are using: OS. name is 'nt 'for Windows, while for Linux/Unix users, it is 'posix' renamed: OS. rename (old, new) creates a multilevel Directory: OS. makedirs (r "c: \ python \ test") to create a single directory: OS. mkdir ("test") gets the file attribute: OS. stat (file): OS. chmod (file) terminates the current process: OS. exit () to get the file size: OS. path. get Size (filename) file operation: OS .mknod(‑test.txt ") Create an empty file fp = open(‑test.txt", w) to open a file directly. If the file does not exist, create the file about open mode: w is opened in write mode, and a is opened in append mode (start from EOF and create a file if necessary) r + open w in read/write mode + open in read/write mode (see w) a + opens in read/write mode (see a) rb opens wb in binary read mode in binary write mode (see w) AB opens 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 +) fp. read ([size]) # size is the read length, in bytes. readline ([size]) # Read a row. If the size is defined, it is possible that only part of the fp of the row is returned. Readlines ([size]) # Use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read only to a part of the file. Fp. write (str) # write str to the file. write () does not add a line break fp after str. writelines (seq) # Write All seq content to a file (multiple rows are written at one time ). This function is only faithfully written without adding anything to the end of each line. Fp. close () # close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, ValueError fp is generated. flush () # Write the buffer content to the hard disk fp. fileno () # returns a long integer "file tag" fp. isatty () # Whether the file is a terminal device file (in unix) fp. tell () # Return the current position of the file operation mark, starting with the file as the origin fp. next () # return the next row, and move the operation mark of the file to the next row. Use a file... When a statement such as in file is called, the next () function is called to implement traversal. Fp. seek (offset [, whence]) # mark the file operation and move it to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. However, if the whence parameter is provided, it is not necessary. If the whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the Operation mark of the file is automatically returned to the end of the file each time the file is written. Fp. truncate ([size]) # crop the file to the specified size. The default value is the location marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content. Directory operation: OS. mkdir ("file") creates a directory to copy the file: shutil. copyfile ("oldfile", "newfile") both oldfile and newfile can only be files shutil. copy ("oldfile", "newfile") oldfile can only be a folder, newfile can be a file, or a destination directory copy Folder: shutil. copytree ("olddir", "newdir") both olddir and newdir can only be directories, and newdir must not exist in the renamed file (directory) OS. rename ("oldname", "newname") files or directories use this command to move the file (directory) shutil. move ("oldpos", "newpos") to delete the file OS. remove ("file") deletes the directory OS. rmdir ("dir") can only delete the empty directory shutil. rmtree ("dir") empty directories and directories with content can be deleted and converted to the OS directory. example 1: add the '_ fc' python code to the names of all images in the folder: #-*-coding: UTF-8-*-import reimport osimport time # str. split (string) split string # 'connector '. join (list) combines the list into a string def change_name (path): global I if not OS. path. isdir (path) and not OS. path. isfile (path): return False if OS. path. isfile (path): file_path = OS. path. split (path) # split the Directory and file lists = file_path [1]. split ('. ') # split the file and the file extension file_ext = lists [-1] # retrieve the suffix (list slicing operation) img_ext = ['bmp', 'jpeg ', 'gif ', 'psd ', 'png', 'jpg '] if file_ext in img_ext: OS. rename (path, file_path [0] + '/' + lists [0] + '_ fc. '+ file_ext) I + = 1 # note that I here is a trap # Or # img_ext = 'bmp | jpeg | gif | psd | png | jpg' # if file_ext in img_ext: # print ('OK-' + file_ext) elif OS. path. isdir (path): for x in OS. listdir (path): change_name (OS. path. join (path, x) # OS. path. join () is useful in path processing. img_dir = 'd: \ xx \ images 'img _ dir = img_dir.replace ('\\','/') start = time. time () I = 0change_name (img_dir) c = time. time ()-startprint ('program running time: % 0.2f '% (c) print ('total % s images processed' % (I) output result: program running time: 0.11 processed a total of 109 Images

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.