Always can't remember the API. Last night, when I wrote this, I didn't remember, so just sort it out:
python The operation of files, folders (file manipulation functions) requires OS modules and 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: File read, create, append, delete, empty
One, create a new file with Python, the content is an integer from 0 to 9, each number occupies one line:
#python
>>>f=open (' F.txt ', ' W ') # R Read Only, W writable, a append
>>>for i in Range (0,10): F.write (str (i) + ' \ n ')
. . .
>>> F.close ()
II, File contents appended, 10 random integers from 0 to 9:
#python
>>>import random
>>>f=open (' F.txt ', ' a ')
>>>for i in Range (0,10): F.write (str (random.randint))
0,9 . .
>>>f.write (' \ n ')
>>>f.close ()
Three, the contents of the file appended, from 0 to 9 of random integers, 10 digits in a row, 10 lines:
#python
>> > Import Random
>>> f=open (' f.txt ', ' a ')
>>> for I in Range (0,10):
. . . for I InRange (0,10): F.write (str (random.randint (0,9)))
. . . f.write (' \ n ')
. . .
>>> F.close ()
Four, direct the standard output to a file:
#python
>>> import sys
>>> sys.stdout = Open (" Stdout.txt "," W ")
>>> ...
V. Reading and writing of documents
First, the file opens:
f = File (name[, mode[,buffering]])
Entry parameters: Name File name
mode option, String
Buffering whether buffered (0= not buffered, 1 = buffered, int number of >1 = buffer size)
Return value: File object
Mode options:
"R" opens in read-only file, exception occurs if the file does not exist
"W" opens in write mode and can only write files if the file does not exist, create the file
If the file already exists, empty it before opening the file
"RB" is opened in binary read mode, only read files, if the file does not exist, an exception occurs
"WB" opens in binary write, can only write files, if the file does not exist, create the file
If the file already exists, empty it before opening the file
"RT" opens as a text read, can only read a file, and if the file does not exist, an exception occurs
"WT" is opened as text, can only write files, if the file does not exist, create the file
If the file already exists, empty it before opening the file
"Rb+" is opened in binary read, can read, write the file, if the file does not exist, an exception will occur
"Wb+" is opened in binary write, can read, write the file, if the file does not exist, create the file
If the file already exists, empty it before opening the file
Second, close the file
F.close ()
When the file is read and written, the file should be closed.
Third, empty the contents of the file
F.truncate ()
Note: Only files opened in writable mode, such as "r+" "rb+" "W" "WB" "wb+" can perform this function.
Iv. pointer positioning and querying of files
(1) file pointer:
When the file is opened, its object is stored in F, which remembers the current location of the file so that it can perform a read, write operation, which is called a pointer to the file (a long type of bytes that starts at the head of the file).
(2) Where the file is opened:
with "R" "r+" "rb+" read mode, "W" "w+" "wb+" to open the file,
At first, the file pointer points to the file's head.
(3) Gets the value of the file pointer:
L= F.tell ()
(4) Pointer to move file
F.seek (offset, option)
option = 0 o'clock, which indicates that the file pointer is pointing from the file header to the "offset" byte.
option = 1 o'clock, which indicates that the file pointer points to the current position of the file and moves the "offset" byte backwards.
option = 2 o'clock, which means pointing the file pointer from the end of the file, moving the "offset" byte forward.
V. Reading from a file means content
1 reading of text files (files opened in "RT" mode)
s = F.readline ()
Return value: S is a string that reads a line from a file with a line terminator.
Description: (1) If Len (s) =0 indicates the end of the file
(2) If it is the last line of the file, there may not be a line terminator
22 binary files (files opened in "RB", "rb+", "wb+") read
s = F.read (n)
Description: (1) If Len (s) =0 indicates the end of the file
(2) After the file has been read, the pointer of the file moves the Len (s) byte backwards.
(3) If the track is bad, an exception occurs.
Six, write a string to the file
F.write (s)
Parameter: s the string to write
Description: (1) After the file has been written, the pointer of the file moves the Len (s) byte backwards.
(2) If the track is bad, or the disk is full, an exception occurs.
Return value: S is a string that reads content from a file
Vii. deletion of files
Import OS
Os.remove (file)
Python file operations