Python file,
File opening function:F = open
Table 1-1: Common Values of Mode Parameters in open Functions
| Open Mode |
Description |
| 'R' |
Read mode |
| 'W' |
Write mode |
| 'A' |
Append Mode |
| 'B' |
Binary Mode |
| '+' |
Read/write mode |
Table 1-2: file object Method
| File object Method |
Perform operations |
| F. close () |
Close file |
| F. read (size =-1) |
Read size characters from the file. When no size is given or a negative value is given, read all the remaining characters and return them as strings. |
| F. readline () |
Open in write mode. If the file exists, append it to the end. |
| F. write (str) |
Write string str to file |
| F. writelines (seq) |
Writing string sequence seq to a file. seq should be an iteratable object that returns a string. |
| F. seek (offset, from) |
Move the file pointer in the file, and offset the offset byte from (0 indicates the start position of the file, 1 indicates the current position, and 2 indicates the end of the file ). |
| F. tell () |
Returns the current position in the file. |
File read/write operations:
1 #!/usr/bin/python2 2 # -*- coding: utf-8 -*- 3 4 def save_file(boy,girl,count): 5 file_name_boy = '/home/wei/wei/test/' + 'boy_' + str(count) + '.txt' 6 file_name_girl = '/home/wei/wei/test/' + 'gilr_' + str(count) + '.txt' 7 8 boy_file = open(file_name_boy, 'w') 9 girl_file = open(file_name_girl, 'w')10 11 boy_file.writelines(boy)12 girl_file.writelines(girl)13 boy_file.close()14 girl_file.close()15 def file_split(filename):16 file = open(filename)17 boy = []18 girl = []19 20 count = 121 for each_line in file:22 if each_line[:6] != '======':23 (role, line_spoken) = each_line.split(':', 1)24 if role == 'a':25 boy.append(line_spoken)26 if role == 'b':27 girl.append(line_spoken)28 else:29 save_file(boy,girl,count)30 boy = []31 girl = []32 count += 133 save_file(boy,girl,count)34 file.close()35 36 file_split(r'/home/wei/wei/test/test.txt')
OS module:
Overview: the python OS module contains common operating system functions.
Common Methods:
1 OS. access (path, mode) # verify the permission mode 2 OS. chdir (path) # change the current working directory 3 OS. chflags (path, flags) # set the path tag as a number tag. 4 OS. chmod (path, mode) # Change permission 5 OS. chown (path, uid, gid) # change the file owner 6 OS. chroot (path) # change the root directory of the current process 7 OS. close (fd) # close the file descriptor fd 8 OS. closerange (fd_low, fd_high) # Close all file descriptors, from fd_low (included) to fd_high (not included). The error will ignore 9 OS. curdir # returns the current directory :('. ') 10 OS. dup (fd) # copy the file descriptor fd11 OS. dup2 (fd, fd2) # copy one file descriptor fd to another fd212 OS. environ # obtain the system environment variable 13 OS. fchdir (fd) # change the current working directory 14 OS through the file descriptor. fchmod (fd, mode) # change the access permission of a file. The file is specified by the fd parameter, and the mode parameter is the file access permission under Unix. 15 OS. fchown (fd, uid, gid) # modify the ownership of a file. This function modifies the user ID and user group ID of a file, which is specified by the file descriptor fd. 16 OS. fdatasync (fd) # forcibly write the file to the disk. The file is specified by the file descriptor fd, but the file status information is not forcibly updated. 17 OS. fdopen (fd [, mode [, bufsize]) # create a file object through the file descriptor fd and return this file object 18 OS. fpathconf (fd, name) # Return the system configuration information of an opened file. Name is the value of the retrieved system configuration. It may be a string that defines the system value. These names are specified in many standards (POSIX.1, Unix 95, Unix 98, and others ). 19 OS. fstat (fd) # Return the state of the file descriptor fd, such as stat (). 20 OS. fstatvfs (fd) # returns information about the file system that contains the file descriptor fd, such as statvfs () 21 OS. fsync (fd) # forcibly write the file with the file descriptor fd to the hard disk. 22 OS. ftruncate (fd, length) # crop the file corresponding to the file descriptor fd, so it cannot exceed the file size. 23 OS. getcwd () # returns the current working directory 24 OS. getcwdu () # returns a Unicode object 25 OS in the current working directory. isatty (fd) # If the file descriptor fd is open and connected to the tty (-like) device, true is returned; otherwise, False is returned. 26 OS. lchflags (path, flags) # set the path tag as a number tag, similar to chflags (), but there is no soft link 27 OS. lchmod (path, mode) # modify the connection File Permission 28 OS. lchown (path, uid, gid) # change the file owner, similar to chown, but do not trace the link. 29 OS. link (src, dst) # create a hard link named dst, pointing to the src30 OS parameter. listdir (path) # returns the list of names of files or folders in the folder specified by path. 31 OS. lseek (fd, pos, how) # set the current position of the file descriptor fd to pos. how to modify it: SEEK_SET or 0 to set the pos calculated from the file; SEEK_CUR or 1 is calculated from the current location; OS. SEEK_END or 2 starts from the end of the file. valid for 32 OS in unix and Windows. lstat (path) # Like stat (), but there is no soft link 33 OS. linesep # The row Terminator used by the current platform. In win, it is \ t \ n, and in Linux it is \ n 34 OS. major (device) # extract the device major number from the original device number (use st_dev or st_rdev field in stat ). 35 OS. makedev (major, minor) # Use the major and minor device numbers to form an original device number 36 OS. makedirs (path [, mode]) # recursive Folder creation function. For example, mkdir (), but all the created intermediate-level folders must contain subfolders. 37 OS. minor (device) # extract the minor number from the original device number (use st_dev or st_rdev field in stat ). 38 OS. mkdir (path [, mode]) # create a folder named path in the numeric mode. The default mode is 0777 (octal ). 39 OS. mkfifo (path [, mode]) # create a named pipe. The mode is a number and the default value is 0666 (octal) 40 OS. mknod (filename [, mode = 0600, device]) # create a file system node named filename (file, device special file, or pipe ). 41 OS. open (file, flags [, mode]) # open a file and set the required open options. The mode parameter is optional for 42 OS. openpty () # open a new Pseudo Terminal Pair. Returns the pty and tty file descriptors. 43 OS. pathconf (path, name) # Return the system configuration information of the relevant file. 44 OS. pathsep # string 45 OS used to split the file path. pardir # obtain the string name of the parent directory of the current directory :('.. ') 46 OS. pipe () # create an MPS queue. returns a pair of file descriptors (r, w) for reading and writing 47 OS respectively. popen (command [, mode [, bufsize]) # open a pipeline from a command for 48 OS. path. abspath (path) # Return the absolute path of path normalization 49 OS. path. split (path) # divide the path into two groups of directories and file names and return 50 OS. path. dirname (path) # returns the path directory. In fact, it is the first element 51 OS. path. basename (path) # of OS. path. split (path) that returns the final file name of path. If the path ends with a slash (/) or slash (\), a null value is returned. That is, OS. path. the second element 52 OS of split (path. path. exists (path) # True is returned if path exists. If path does not exist, False53 OS is returned. path. isabs (path) # If path is an absolute path, return True54 OS. path. isfile (path) # If path is an existing file, True is returned. Otherwise, False55 OS. path. isdir (path) # If path is an existing Directory, True is returned. Otherwise, False56 OS is returned. path. join (path1 [, path2 [,...]) # If multiple paths are combined, the parameters before the first absolute path are ignored. 57 OS. path. getatime (path) # Return the last access time of the file or directory pointed to by path 58 OS. path. getmtime (path) # Return the last modification time of the file or directory pointed to by path 59 OS. name # string indicates the current platform. Win-> 'nt '; Linux-> 'posix' 60 OS. read (fd, n) # reads up to n Bytes from the file descriptor fd and returns a string containing the read bytes. The file descriptor fd corresponds to the end of the file and returns an empty string. 61 OS. readlink (path) # Return the file 62 OS. remove (path) pointed to by the soft link # delete the file whose path is path. If path is a folder, OSError will be thrown; check the following rmdir () to delete a directory. 63 OS. removedirs (path) # recursively delete directories. If the directory is empty, delete it and recursively go to the upper-level directory. If the directory is empty, delete it and push 64 OS accordingly. rename (src, dst) # rename the file or directory, from src to dst65 OS. renames (old, new) # recursively rename the directory or rename the file. 66 OS. rmdir (path) # Delete the empty directory specified by path. If the directory is not empty, an OSError exception is thrown. 67 OS. sep # specifies the path delimiter of the operating system. In win, the path is \, and in Linux, the path Delimiter is "/" 68 OS. stat (path) # gets the information of the path specified by path, which is equivalent to the stat () System Call in c api. 69 OS. stat_float_times ([newvalue]) # determines whether stat_result displays the timestamp 70 OS as a float object. statvfs (path) # obtain the statistics of the file system in the specified path 71 OS. symlink (src, dst) # create a soft link 72 OS. system ("bash command") # Run the shell command to directly display 73 OS. tcgetpgrp (fd) # Return with the terminal fd (one by OS. open () returned open file descriptor) associated process group 74 OS. tcsetpgrp (fd, pg) # Set and end fd (one by OS. the open file descriptor returned by open () is associated with the pg process group. 75 OS. tempnam ([dir [, prefix]) # Return the unique path name used to create a temporary file. 76 OS. tmpfile () # Return a file object in the open mode (w + B). This file object will be automatically deleted without a folder entry and a file descriptor. 77 OS. tmpnam () # returns a unique path 78 OS. ttyname (fd) for creating a temporary file # returns a string that represents the terminal device associated with the file descriptor fd. If fd is not associated with a terminal device, an exception is thrown. 79 OS. unlink (path) # delete the file path 80 OS. utime (path, times) # Return the access time and modification time of the specified path file. 81 OS. walk (top [, topdown = True [, onerror = None [, followlinks = False]) # output the file name in the folder to move up or down in the middle of the tree. 82 OS. write (fd, str) # write a string to the file descriptor fd. Return the length of the actually written string.