>>> Import os>>> os.path.exists (' d:/assist ') true>>> os.path.exists (' d:/assist/ getteacherlist.py ') true>>> os.path.isfile (' d:/assist ') false>>> os.path.isfile (' d:/assist/ getteacherlist.py ') true>>> os.makedirs (' D:/assist/set ') >>> os.path.exists (' D:/assist/set ') True
files, folders in Python (file manipulation function) operation requires an OS module and a shutil module.
Get the current working directory, that is, the directory path of the current Python script work: OS.GETCWD ()
Returns all files and directory names under the specified directory name: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 ()
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 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 variables:os.getenv () and os.putenv ()
Gives the line terminator used by the current platform:os.linesep 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 permissions and timestamps:os.chmod (file)
Terminate 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 part of a row
fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the 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 after Str
fp.writelines (seq) #把seq的内容全部写到文件中 (multi-line write-once). This function simply writes faithfully and does not add anything behind each line.
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. If a file is closed and then manipulated, it generates VALUEERROR
Fp.flush () #把缓冲区的内容写入硬盘
Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () #文件是否是一个终端设备文件 (on UNIX systems)
Fp.tell () #返回文件操作标记的当前位置, starting with the origin of the file
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 a 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 may 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")The file or directory is used by this command
Moving Files (directories)
shutil.move ("Oldpos", "Newpos")
deleting files
os.remove ("file")
Delete Directory
os.rmdir ("dir")Only empty directories can be deleted
shutil.rmtree ("dir")Empty directories, 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 re
Import OS
Import time
#str. Split (string) split string
# ' connectors '. Join (list) to make a 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 = 0
Change_name (Img_dir)
c = Time.time ()-Start
Print (' 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 determines whether files and folders exist, creates folders