Operations on files, folders (file action functions) in
python need to involve OS modules and Shutil modules.
Get the current working directory, the directory path of the current Python script work: OS.GETCWD ()
Returns all the file and directory names under the specified directory: os.listdir ()
function to delete a file: Os.remove ()
Delete multiple directories: Os.removedirs (r "C:\python")
Verify that the given path is a file: Os.path.isfile ()
Verify that the given path is a directory: Os.path.isdir ()
Determine if it is an absolute path: Os.path.isabs ()
Verify that the given path is true: 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 ') results: ('/home/swaroop/byte/code ', ' poem.txt ')
Detach extension: Os.path.splitext ()
Get path name: Os.path.dirname ()
Get filename: os.path.basename ()
Run shell command: Os.system ()
Reading and setting Environment variables: os.getenv () and os.putenv ()
give the line terminator used by the current platform:os.linesep windows use ' \ r \ n ', Linux use ' \ N ' While the Mac uses ' \ R '
to indicate the platform you are 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 files Permissions and timestamp: os.chmod (file)
Terminates the current process: Os.exit ()
Get file Size: os.path.getsize (filename)
File actions:
Os.mknod ("Test.txt") creates an empty file
fp = open ("Test.txt", W) opens a file directly and creates a file if it does not exist
About open mode:
W opens in write mode,
A opens in Append mode (starting with EOF, creating a new file if necessary)
R+ Open in read-write mode
w+ opens in read-write mode (see W)
A + is opened 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 and write mode (see r+)
Wb+ opens in binary read and write mode (see w+)
Ab+ opens in binary read and write mode (see A +)
Fp.read ([size]) #size为读取的长度, in bytes
Fp.readline ([size]) #读一行, if size is defined, it is possible to return only part of a row
Fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns to this list. In fact, its internal is through the Loop call ReadLine () to achieve. If the size argument is supplied, the size is the total length of the read content, meaning that it may be read only as part of the file.
Fp.write (str) #把str写到文件中, write () does not add a newline character after Str
Fp.writelines (seq) #把seq的内容全部写到文件中 (multiple lines of one-time write). This function is also written faithfully and does not add anything behind each line.
Fp.close () #关闭文件. Python will automatically close a file after a file is not used, but this feature is not guaranteed, it is best to develop their own habit of shutting down. If a file is turned on after it has been closed it will produce valueerror
Fp.flush () #把缓冲区的内容写入硬盘
Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () #文件是否是一个终端设备文件 (in Unix systems)
Fp.tell () #返回文件操作标记的当前位置, at the beginning of the file as the origin
Fp.next () #返回下一行, and the file action tag is shifted to the next line. When you use a file for a statement such as. in file, you call the next () function to iterate through it.
Fp.seek (Offset[,whence]) #将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file, typically a positive number. However, if the whence parameter is provided, the whence can be calculated from scratch for 0, and 1 indicates the current position is the origin calculation. 2 indicates that the origin is computed at the end of the file. Note that if the file is opened in a A or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is performed.
Fp.truncate ([size]) #把文件裁成规定的大小, the default is the location where the current file action tag is to be trimmed. If the size is larger than a file, depending on the system, you may not change the file, or you can use 0 to make up the file to the appropriate size, or you can add some random content.
Directory Operations:
Os.mkdir ("file") Create a directory
Copy files:
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 target 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, content directory can be deleted
Convert Directory
Os.chdir ("path") Change path
Related examples
1 Add "_fc" to all picture names under the folder
Python code:
#-*-coding:utf-8-*-import re import os import time #str. Split (String) splits the string # ' connectors '. Join (list) makes up a string def change_name (
Path): Global I if not os.path.isdir (path) and 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] #取出 Suffix name (list slicing operation) Img_ext = [' bmp ', ' jpeg ', ' gif ', ' psd ', ' png ', ' jpg '] if file_ext in Img_ext:os.rename (path,file_pat h[0]+ '/' +lists[0]+ ' _fc. ' +file_ext) i+=1 #注意这里的i是一个陷阱 #或者 #img_ext = ' bmp|jpeg|gif|psd|png|jpg ' #if file_ext in Img_ext: # p Rint (' 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 handling Img_dir = ' d:\\xx\\xx\\images ' Img_dir = img_dir.replace (' \ ', '/') start = Time.time () i = 0 Cha Nge_name (img_dir) c = time.time ()-Start print (' program run time:%0.2f '% (c)) "Print (' total%s picture '% (i))
Output results:
Program Run time: 0.11
109 Photos processed in total
Examples of Python common file operations
Path name Access function in Os.path module
Separated
basename () Remove directory path, return filename
DirName () Remove filename, return directory path
Join () combines the separated parts into a path name
Split () return (DirName (), basename ()) tuple
Splitdrive () return (drivename, pathname) tuple
Splitext () returns (filename, extension) tuple
Information
Getatime () returns the most recent access time
Getctime () return file creation time
Getmtime () returns the most recent 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): Determines if name is a directory, name is not a directory returns false
Os.path.isfile (name): Determines whether name is a file, does not exist name also returns false
Os.path.exists (name): Determines whether a file or directory name exists
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 filename, and it will not determine whether the file or directory exists)
Os.path.splitext (): Detach file name and extension
Os.path.join (path,name): Connecting directories with file names or directories
Os.path.basename (PATH): Return file name
Os.path.dirname (path): Back to File path
File operations in the OS module:
OS Module Properties
Linesep the string used to separate rows in a file
A string that the SEP uses to separate the file path names
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. Listing files under the directory: Os.listdir (PATH)
4. Get the current working directory: OS.GETCWD ()
5. Change 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 properties: Os.stat (file)
11. Modify file permissions and timestamp: os.chmod (file)
12. Execute operating system command: Os.system ("dir")
13. Start a new process: Os.exec (), OS.EXECVP ()
14. In the background execution procedure: OSSPAWNV ()
15. Terminate the current process: Os.exit (), Os._exit ()
16. Separate 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 FileName: 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 it is an absolute path: Os.path.isabs (r ". \python\")--> False
22. Determine whether the directory: Os.path.isdir (r "C:\python")--> True
23. Judge whether it is a file: Os.path.isfile (r "c:\python\hello.py")--> True
24. Determine if the link 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 directory for all Files: Os.path.walk ()
Shutil module actions on files:
1. Copy a single file: Shultil.copy (Oldfile, Newfle)
2. Copy the entire tree: Shultil.copytree (r ". \setup", R ". \backup")
3. Delete entire directory tree: Shultil.rmtree (r. \backup)
Actions 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 into memory file data: Print F.read () #或print f.getvalue ()--> Hello world!
3. Write data to memory file: F.write ("Good day!")
4. Close Memory File: F.close ()
Import OS
import os.path import
unittest
import time
#import Pygame
class 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 ') #第二个参数是默认的, can not add
#读二进制文件:
input = open (' Data ', ' RB ')
#读取所有文件内容:
open (' Xxoo.txt '). Read ()
#读取固定字节
open (' abinfile ', ' RB '). Read (MB)
#读每行
File_object.readlines ()