Python file Read and write operation example detailed _python

Source: Internet
Author: User
Tags readline file permissions python script

A, python in the file, folder operations often used in the OS module and Shutil module common methods.
1. Get the current working directory, that is, the current Python script work directory path: OS.GETCWD ()
2. Returns all files and directory names under the specified directory: Os.listdir ()
3. function to delete a file: Os.remove ()
4. Delete multiple directories: Os.removedirs (r "C:\python")
5. Verify that the given path is a file: Os.path.isfile ()
6. Verify that the given path is a directory: Os.path.isdir ()
7. Determine whether the absolute path: Os.path.isabs ()
8. Verify that the given path is really stored: os.path.exists ()
9. Returns the directory name and filename of a path: Os.path.split ()
Example:

Copy Code code as follows:
Os.path.split ('/home/swaroop/byte/code/poem.txt ') results: ('/home/swaroop/byte/code ', ' poem.txt ')

10. Detach extension: Os.path.splitext ()
11. Get Path name: Os.path.dirname ()
12. Get filename: Os.path.basename ()
13. Run shell command: Os.system ()
14. Read and SET environment variables: os.getenv () and os.putenv ()
15. Give the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '
16. Indicate the platform you are using: Os.name for Windows, it is ' NT ', and for Linux/unix users, it's ' POSIX '
17. Renaming: Os.rename (old, new)
18. Create a multilevel directory: Os.makedirs (r "C:\python\test")
19. Create a single directory: Os.mkdir ("Test")
20. Get File properties: Os.stat (file)
21. Modify file permissions and timestamp: os.chmod (file)
22. Terminate the current process: Os.exit ()
23. Get File Size: os.path.getsize (filename)
Second, the document operation method Daquan
1.os.mknod ("Test.txt") creates an empty file
2.FP = open ("Test.txt", W) opens a file directly and creates a file if it does not exist
3. About open mode:
Copy Code code as follows:
W: Open in write mode,
A: Open in Append mode (start with EOF, create new file if necessary)
r+: Open in read-write mode
w+: Open in read/write mode (see W)
A +: Open in read/write mode (see a)
RB: Open in binary read mode
WB: Open in binary write mode (see W)
AB: Open in binary append mode (see a)
rb+: Open in binary read and write mode (see r+)
wb+: Open in binary read and write mode (see w+)
ab+: Open 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.
Three, directory operation method Encyclopedia
1. Create a table of contents
Os.mkdir ("file")
2. Copy files:
Shutil.copyfile ("Oldfile", "NewFile") #oldfile和newfile都只能是文件
Shutil.copy ("Oldfile", "NewFile") #oldfile只能是文件夹, NewFile can be a file, or it can be a target directory
3. Copy folder:
4.shutil.copytree ("Olddir", "Newdir") #olddir和newdir都只能是目录, and newdir must not exist
5. Renaming files (directories)
Os.rename ("Oldname", "NewName") #文件或目录都是使用这条命令
6. Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")
7. Delete Files
Os.remove ("file")
8. Delete Directory
Os.rmdir ("dir") #只能删除空目录
Shutil.rmtree ("dir") #空目录, content directory can be deleted
9. Convert Directory
Os.chdir ("path") #换路径
Iv. Examples of comprehensive documentation operations
Add ' _fc ' to all picture names under the folder
Python code:
Copy Code code as follows:
#-*-Coding:utf-8-*-
Import re
Import OS
Import time
#str. Split (string) split string
# ' connectors '. Join (list) to make lists into 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 slicing 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 for path handling

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 runs time consuming:%0.2f '% (c))
Print (' A total of%s pictures '% (i))


Output results:
Copy Code code as follows:
Program Run time: 0.11
109 Photos processed in total

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.