Python file operation api (file operation function ),

Source: Internet
Author: User

Python file operation api (file operation function ),

Operations on files and folders (file operation functions) in python involve the OS module and the shutil module.

Get the current working directory, that is, the directory path for the current Python script: OS. getcwd ()
Returns all files and directories in the specified directory named OS. listdir ()
The function is used to delete a file: OS. remove ()
Delete multiple directories: OS. removedirs (r "c: \ python ")
Check whether the given path is a file: OS. path. isfile ()
Check whether the given path is a directory: OS. path. isdir ()
Determine whether the path is absolute: OS. path. isabs ()
Check whether the given path is saved: 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 ()
Get the path: OS. path. dirname ()
Get File Name: OS. path. basename ()
Run the shell command: OS. system ()
Read and set environment variables: OS. getenv () and OS. putenv ()
The line terminator used by the current platform is given: OS. linesep for Windows uses '\ r \ n', Linux uses' \ n', and Mac uses '\ R'
Indicates the platform you are using: OS. name for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix'
Rename: OS. rename (old, new)
Create a multilevel Directory: OS. makedirs (r "c: \ python \ test ")
Create a single directory: OS. mkdir ("test ")
Get file attributes: OS. stat (file)
Modify file permission and timestamp: OS. chmod (file)
Terminate the current process: OS. exit ()
Get file size: OS. path. getsize (filename)

File Operations:
OS. mknod ("test.txt") to create an empty file
Fp = open ("test.txt", w) open a file directly. If the file does not exist, create a file.

About open mode:

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 +)

Fp. read ([size]) # size indicates the read length, in bytes.
Fp. readline ([size]) # Read a row. If the size is defined, only one part of the row may be returned.
Fp. 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 linefeed after str.
Fp. 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 is generated.
Fp. 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 line and move the operation mark of the file to the next line. 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") to create a directory
Copy a 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 target directory.
Copy Folder:
Shutil. copytree ("olddir", "newdir") both olddir and newdir can only be directories, and newdir must not exist
Rename a file (directory)
OS. rename ("oldname", "newname") files or directories all use this command
Move a file (directory)
Shutil. move ("oldpos", "newpos ")
Delete an object
OS. remove ("file ")
Delete directory
OS. rmdir ("dir") can only delete empty directories
Shutil. rmtree ("dir") empty directories and directories with content can be deleted.
Conversion directory
OS. chdir ("path") change path

Example

1. Add '_ fc' to the names of all images in the folder'

Python code:

#-*-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 ('% s images processed in total' % (I ))

Output result:

Running Duration: 0.11
109 images processed in total

Python common file operation examples

Path Name access function in the OS. path Module
Separate
Basename () removes the directory path and returns the file name.
Dirname () removes the file name and returns the directory path.
Join () combines the separated parts into a path name
Split () returns the (dirname (), basename () tuples.
Splitdrive () returns the (drivename, pathname) tuples
Splitext () returns the (filename, extension) tuples

Information
Getatime () returns the last access time
Getctime () returns the File Creation Time
Getmtime () returns the last file modification time
Getsize () returns the file size (in bytes)

Query
Exists () specifies whether the path (file or directory) exists
Isabs () specifies whether the path is an absolute path
Isdir () specifies whether the path exists and is a directory
Isfile () specifies whether the path exists and is a file
Islink () specifies whether the path exists and is a symbolic link.
Ismount () specifies whether the path exists and is a mount point
Whether two samefile () path names point to the same file

OS. path. isdir (name): determines whether the name is a directory. If the name is not a directory, false is returned.
OS. path. isfile (name): determines whether the name is a file. If the name does not exist, false is returned.
OS. path. exists (name): determines whether a file or directory name exists.
OS. path. getsize (name): Get the file size. If the name is a directory, return 0L
OS. path. abspath (name): Obtain the absolute path.
OS. path. normpath (path): standard path string format
OS. path. split (name): split the file name and directory (in fact, if you fully use the directory, it will also separate the last directory as the file name, and it will not determine whether the file or directory exists)
OS. path. splitext (): separates file names and extensions
OS. path. join (path, name): Connection directory and file name or directory
OS. path. basename (path): returns the file name.
OS. path. dirname (path): Return file path


File Operations in the OS module:
OS module attributes
Linesep is a string used to split rows in a file.
A string used to separate the file path name.
Pathsep is a string used to separate file paths.
String name of the current working directory of curdir
Pardir (current working directory) parent directory string name

1. rename: OS. rename (old, new)

2. Delete: OS. remove (file)
3. List the files in the directory: OS. listdir (path)
4. Get the current working directory: OS. getcwd ()
5. Change the working directory: OS. chdir (newdir)
6. Create a multilevel Directory: OS. makedirs (r "c: \ python \ test ")
7. Create a single directory: OS. mkdir ("test ")
8. Delete multiple directories: OS. removedirs (r "c: \ python") # delete all empty directories in the last directory of the given path.
9. delete a single directory: OS. rmdir ("test ")
10. Get file attributes: OS. stat (file)
11. Modify the file Permission and timestamp: OS. chmod (file)
12. Execute the operating system command: OS. system ("dir ")
13. Start a new process: OS .exe c (), OS .exe cvp ()
14. Execute the program in the background: osspawnv ()
15. Terminate the current process: OS. exit (), OS. _ exit ()
16. Separated file name: OS. path. split (r "c: \ python \ hello. py") --> ("c: \ python", "hello. py ")
17. separation Extension: OS. path. splitext (r "c: \ python \ hello. py ") --> (" c: \ python \ hello ",". py ")
18. Obtain the path name: OS. path. dirname (r "c: \ python \ hello. py") --> "c: \ python"
19. Get the file name: OS. path. basename (r "r: \ python \ hello. py") --> "hello. py"
20. Determine whether the file exists: OS. path. exists (r "c: \ python \ hello. py") --> True
21. Determine whether the path is absolute: OS. path. isabs (r ". \ python \") --> False
22. Check whether the directory is OS. path. isdir (r "c: \ python") --> True
23. Determine whether the file is: OS. path. isfile (r "c: \ python \ hello. py") --> True
24. Determine whether the file is a linked file: OS. path. islink (r "c: \ python \ hello. py") --> False
25. Get file size: OS. path. getsize (filename)
26. *******: OS. ismount ("c: \") --> True
27. Search all files in the directory: OS. path. walk ()

Operations on files by the shutil module:
1. copy a single file: shultil. copy (oldfile, newfle)

2. Copy the entire directory tree: shultil. copytree (r ". \ setup", r ". \ backup ")

3. Delete the entire directory tree: shultil. rmtree (r ". \ backup ")

Temporary File Operations:
1. Create a unique temporary file: tempfile. mktemp () --> filename

2. Open the temporary file: tempfile. TemporaryFile ()

Memory file (StringIO and cStringIO) Operations
[4. StringIO] # cStringIO is a fast implementation module of the StringIO module.

1. Create a memory file and write the initial data: f = StringIO. StringIO ("Hello world! ")
2. read Memory file data: print f. read () # or print f. getvalue () --> Hello world!
3. write Data to memory files: f. write ("Good day! ")
4. close the memory file: f. close ()

import osimport os.pathimport unittestimport time#import pygameclass PyFileCommonOperatorTest(unittest.TestCase):  def __init__(self):    """constructor"""    def test01(self):    print os.linesep    print os.sep    print os.pathsep    print os.curdir    print os.pardir    print os.getcwd()    print 'unittest here'if __name__ == "__main__":  t = PyFileCommonOperatorTest()  t.test01()

Writing a Read File

# Writing a Read File: # reading a text file: input = open ('data', 'R') # The second parameter is default. You can leave it blank. # Read a binary file: input = open ('data', 'rb') # Read all file content: open('xxoo.txt '). read () # read the fixed byte open ('abinfile', 'rb '). read (100) # read each row of file_object.readlines ()

Related Article

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.