Python file read/write operations

Source: Internet
Author: User

I. Common Methods of operating OS modules and shutil modules for files and folders in python.
1. Get the current working directory, that is, the directory path of the current Python script: OS. getcwd ()
2. Return all files and directory names in the specified directory: OS. listdir ()
3. The function is used to delete a file: OS. remove ()
4. Delete multiple directories: OS. removedirs (r "c: \ python ")
5. Check whether the given path is a file: OS. path. isfile ()
6. Check whether the given path is a directory: OS. path. isdir ()
7. Determine whether the path is absolute: OS. path. isabs ()
8. Check whether the given path is actually saved: OS. path. exists ()
9. Return the directory name and file name of a path: OS. path. split ()
Copy codeThe code is as follows: OS. path. split ('/home/swaroop/byte/code/poem.txt') Result: ('/home/swaroop/byte/Code', 'poem.txt ')
10. Separation Extension: OS. path. splitext ()
11. Obtain the path: OS. path. dirname ()
12. Get the file name: OS. path. basename ()
13. Run the shell command: OS. system ()
14. Read and set environment variables: OS. getenv () and OS. putenv ()
15. The line terminator used by the current platform is provided: OS. linesep for Windows uses '\ r \ n', Linux uses' \ n', and Mac uses '\ R'
16. indicates the platform you are using: OS. name for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix'
17. rename: 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 attributes: OS. stat (file)
21. Modify the file Permission and timestamp: OS. chmod (file)
22. Terminate the current process: OS. exit ()
23. Get file size: OS. path. getsize (filename)
Ii. File Operations
1. OS. mknod ("test.txt") to create an empty file
2. fp = open ("test.txt", w) open a file directly. If the file does not exist, create the file.
3. About open mode:
Copy codeThe Code is as follows: w: open in write mode,
A: open in append mode (create a file when necessary, starting from EOF)
R +: open in read/write mode
W +: open in read/write mode (see w)
A +: open in read/write mode (see)
Rb: enabled in binary read mode
Wb: open in binary write mode (see w)
AB: open in binary append mode (see)
Rb +: open in binary read/write mode (see r +)
Wb +: open in binary read/write mode (see w +)
AB +: open in binary read/write mode (see a +)
Fp. read ([size]) # size indicates the read length, in bytes.
Fp. readline ([size]) # Read a row. If the size is defined, only one part of the row may be returned.
Fp. readlines ([size]) # Use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read only to a part of the file.
Fp. write (str) # write str to the file. write () does not add a linefeed after str.
Fp. writelines (seq) # Write All seq content to a file (multiple rows are written at one time ). This function is only faithfully written without adding anything to the end of each line.
Fp. close () # close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, ValueError is generated.
Fp. flush () # Write the buffer content to the hard disk
Fp. fileno () # returns a long integer "file tag"
Fp. isatty () # Whether the file is a terminal device file (in unix)
Fp. tell () # Return the current position of the file operation mark, starting with the file as the origin
Fp. next () # return the next line and move the operation mark of the file to the next line. Use a file... When a statement such as in file is called, the next () function is called to implement traversal.
Fp. seek (offset [, whence]) # mark the file operation and move it to the offset position. 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, it is not necessary. If the whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the Operation mark of the file is automatically returned to the end of the file each time the file is written.
Fp. truncate ([size]) # crop the file to the specified size. The default value is the location marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content.
Iii. Directory operations
1. Create a directory
OS. mkdir ("file ")
2. copy the file:
Shutil. copyfile ("oldfile", "newfile") # Both oldfile and newfile can only be files.
Shutil. copy ("oldfile", "newfile") # oldfile can only be a folder. newfile can be a file or a target directory.
3. Copy the folder:
4. shutil. copytree ("olddir", "newdir") # Both olddir and newdir can only be directories, and newdir must not exist
5. Rename the file (directory)
OS. rename ("oldname", "newname") # This command is used for files or directories.
6. Move a file (directory)
Shutil. move ("oldpos", "newpos ")
7. delete an object
OS. remove ("file ")
8. delete a directory
OS. rmdir ("dir") # Only empty directories can be deleted.
Shutil. rmtree ("dir") # You can delete empty directories and directories with content.
9. Conversion directory
OS. chdir ("path") # change path
Iv. file operation examples
Add '_ fc' to the names of all images in the folder'
Python code:
Copy codeThe Code is as follows: #-*-coding: UTF-8 -*-
Import re
Import OS
Import time
# Str. split (string) split string
# 'Connector '. join (list) combines the list into a string
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) # split the Directory and file
Lists = file_path [1]. split ('.') # split the file and file extension
File_ext = lists [-1] # retrieve the suffix (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 # note that I here is a trap
# Or
# 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 \ images'
Img_dir = img_dir.replace ('\\','/')
Start = time. time ()
I = 0
Change_name (img_dir)
C = time. time ()-start
Print ('runtime: % 0.2f '% (c ))
Print ('% s images processed in total '% (I ))
Output result:
Copy codeThe Code is as follows: running time: 0.11
109 images 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: 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.