The operation of files, folders (file manipulation functions) in Python involves both the OS module and the Shutil module.
The
Gets the current working directory, which is the directory path of the current Python script work: OS.GETCWD ()
Returns all files and directory names under the specified directory: os.listdir ()
function to delete a file: Os.remove ()
Delete multiple directories: Os.removedirs (r "C:\python")
verifies whether the given path is a file: Os.path.isfile ()
verifies whether the given path is a directory: Os.path.isdir ()
Determine if absolute path: Os.path.isabs ()
verifies that the given path is really 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 ')
Detach Extension: Os.path.splitext ()
Get path name: Os.path.dirname ()
Get file name: Os.path.basename ()
Run shell command: Os.system ()
Read and SET environment variable: os.getenv () With os.putenv ()
gives the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '
to indicate the platform you're using: Os.name for Windows, It is ' NT ', and for Linux/unix users, it is ' POSIX '
renamed: Os.rename (old, new)
to create a multilevel directory: Os.makedirs (r "C:\python\test")
Create a single directory: Os.mkdir ("test")
Get file properties: Os.stat (file)
Modify permissions and Timestamps: Os.chmod (file)
Terminates the current process: Os.exit ()
Get File Size: os.path.getsize (filename)
File operation:
Os.mknod ("test.txt") Create an empty file
fp = open ("Test.txt", W) opens a file directly and creates a file if the file does not exist
About open mode:
W opens in write mode,
A opens in Append mode (starting with EOF and creating a new file if necessary)
R+ Open in read-write mode
w+ Open in read/write mode (see W)
A + opens in read/write mode (see a)
RB opens in binary read mode
WB opens in binary write mode (see W)
AB opens in binary append mode (see a)
Rb+ opens in binary read/write mode (see r+)
Wb+ opens in binary read/write mode (see w+)
Ab+ opens in binary read/write mode (see A +)
Fp.read ([size]) #size为读取的长度, in bytes
Fp.readline ([size]) #读一行, if size is defined, it is possible to return only one part of the line
Fp.readlines ([ Size]) #把文件每一行作为一个list的一个成员 and return to this list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the file.
Fp.write (str) #把str写到文件中, write () does not add a newline character
Fp.writelines (seq) #把seq的内容全部写到文件中 after str (multi-line write-once). This function simply writes faithfully and does not add anything behind each line. The
Fp.close () #关闭文件. Python will automatically close files after a file is not used, but this feature is not guaranteed and it is best to develop a habit of shutting them down. ValueError
Fp.flush () #把缓冲区的内容写入硬盘
Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () # If a file is also manipulated after it has been closed Whether the file is a terminal device file (Unix system)
Fp.tell () #返回文件操作标记的当前位置, #返回下一行 the beginning of the file as the Origin
Fp.next (), and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal.
Fp.seek (offset[,whence]) #将文件打操作标记移到offset的位置. 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, whence can be calculated from scratch for 0, and 1 for the current position as its origin. 2 means that the end of the file is calculated as the origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made.
Fp.truncate ([size]) #把文件裁成规定的大小, the default is the location that is cropped to the current file action tag. 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.
Directory Operations:
Os.mkdir ("file") Create directory
To copy a file:
Shutil.copyfile ("Oldfile", "NewFile") Oldfile and NewFile can only be files
Shutil.copy ("Oldfile", "NewFile") Oldfile can only be a folder, NewFile can be a file, or it can be a destination directory
To copy a folder:
Shutil.copytree ("Olddir", "Newdir") Olddir and Newdir can only be directories, and newdir must not exist
Renaming files (directories)
Os.rename ("Oldname", "newname") files or directories are all using this command
Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")
deleting files
Os.remove ("file")
Delete Directory
Os.rmdir ("dir") can only delete empty directories
Shutil.rmtree ("dir") empty directory, contents of the directory can be deleted
Converting catalogs
Os.chdir ("path") Change path
Related examples
1 Add ' _fc ' to all picture names under the folder
Python code:
#-*-Coding:utf-8-*-import reimport osimport time#str.split (String) Split string # ' connector '. Join (list) composes the list of strings 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) #分割出目录与文件 lists = File_path[1].split ('. ') #分割出文件与文件扩展名 file_ext = lists[-1] #取出后缀名 (list slice 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 #注意这里的i是一个陷阱 #或者 #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\\xx\\images ' Img_dir = img_dir.replace (' \ \ ', '/') ) start = Time.time () i = 0change_name (img_dir) c = time.time ()-Startprint (' program run time:%0.2f '% (c)) print (' Total processed%s picture '% (i))
Output Result:
Program Run time: 0.11
Processed 109 pictures in total
Python common file Operations examples
Path name access functions in the Os.path module
Separated
basename () Remove directory path, return file name
DirName () Remove file name, return directory path
Join () combines parts of the separation into one path name
Split () return (DirName (), basename ()) tuple
Splitdrive () return (drivename, pathname) tuple
Splitext () return (filename, extension) tuple
Information
Getatime () returns the last access time
Getctime () returns file creation time
Getmtime () returns the last file modification time
GetSize () returns the file size (in bytes)
Inquire
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
Samefile () Two path names pointing to the same file
Os.path.isdir (name): Determine if Name is a directory, name is not a directory and return false
Os.path.isfile (name): Determine if name is not a file, does not exist name also returns false
Os.path.exists (name): Determine if there is a file or directory name
Os.path.getsize (name): Get file size, if name is directory return 0L
Os.path.abspath (name): Get absolute path
Os.path.normpath (PATH): Canonical path string form
Os.path.split (name): Split file name and directory (in fact, if you use the directory completely, 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 (): Detach file name and extension
Os.path.join (path,name): Connection directory with file name or directory
Os.path.basename (PATH): Return file name
Os.path.dirname (PATH): Return file path
File operations in the OS module:
OS Module Properties
Linesep string used to separate rows in a file
The string that Sep uses to separate the file path name
Pathsep string used to separate file paths
CurDir the string name of the current working directory
Pardir (current working directory) parent directory string Name
1. Renaming: Os.rename (old, new)
2. Delete: Os.remove (file)
3. List files in directory: Os.listdir (PATH)
4. Get current working directory: OS.GETCWD ()
5. Change of 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") #删除所给路径最后一个目录下所有空目录.
9. Delete a single directory: Os.rmdir ("Test")
10. Get File attributes: Os.stat (file)
11. Modify file permissions and timestamps: Os.chmod (file)
12. Execute operating system command: Os.system ("dir")
13. Start a new process: Os.exec (), OS.EXECVP ()
14. Executing the program in the background: OSSPAWNV ()
15. Terminate the current process: Os.exit (), Os._exit ()
16. Detach file Name: Os.path.split (r "c:\python\hello.py")--("C:\\python", "hello.py")
17. Detach Extension: Os.path.splitext (r "c:\python\hello.py")--("C:\\python\\hello", ". Py")
18. Get path name: Os.path.dirname (r "c:\python\hello.py")--"C:\\python"
19. Get File Name: Os.path.basename (r "r:\python\hello.py")--"hello.py"
20. Determine if the file exists: os.path.exists (r "c:\python\hello.py")---True
21. Determine if absolute path: Os.path.isabs (r ". \python\")---False
22. Determine if it is a directory: Os.path.isdir (r "C:\python")--True
23. Determine if it is a file: Os.path.isfile (r "c:\python\hello.py")---True
24. Determine if it 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 directory: Os.path.walk ()
Shutil the operation of the module to the file:
1. Copying individual files: shultil.copy (Oldfile, Newfle)
2. Copy Entire directory tree: Shultil.copytree (r ". \setup", R ". \backup")
3. Delete entire directory tree: Shultil.rmtree (r ". \backup")
Operations for temporary files:
1. Create a unique temporary file: tempfile.mktemp ()---filename
2. Open temporary file: tempfile. Temporaryfile ()
Memory files (Stringio and Cstringio) operations
[4.StringIO] #cStringIO是StringIO模块的快速实现模块
1. Create the memory file and write the initial data: F = Stringio.stringio ("Hello world!")
2. Read in memory file data: Print F.read () #或print f.getvalue ()--Hello world!
3. Want the memory file to write data: 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 ()
How to read a document
#读文件的写法: #读文本文件: input = open (' Data ', ' R ') #第二个参数是默认的, you can not add a # Read binary file: input = open (' Data ', ' RB ') #读取所有文件内容: Open (' xxoo.txt '). Read () #读取固定字节open (' Abinfile ', ' RB '). Read (+) #读每行file_object. ReadLines ()