1. Basic File Operations
1. Create and open files
Format:
file = open(filename,arguments) #Parameter description: #File: Customize, open, or create how the file will appear in the program #filename: Direct or relative path to write a file, if there is one, open it to read # When followed by w,w+,a, or a+, create a file and open it if it is not present #arguments: is a parameter, has r,rb,r+,w,wb,w+,a,ab,a+, etc.
Example:
f = open('file', 'w') #Open file in current directory in write-only mode
2. Close Files
After opening the file, you need to close it in time to avoid unnecessary damage to the file.
Format:
file.close() #File Opens the file for you with a custom name
3. Use with statement when opening file
Recommendation: The with statement automatically closes an open file after execution
Format:
with expression as target: with-body #Parameter description: #Expression: Specifies an expression, which can be an open() function that opens a file #target: A variable that stores the result of a run in an expression in this variable #with-body:with statement body, some action statements
Example:
with open('/mnt/file','r') as f: print(f.read()) Run result: Life is short, I learn Python!
4. Writing File Contents
file.write(string) #File Opens the file for you with a custom name #String is a written string
Note: To write information, you need to specify that the open mode is writable when you open the file!
Related parameters:
w: Open file in write-only mode w+: After opening the file, first empty the original content, have read and write permissions on the file A: Open a file in append mode (write at the end of the file contents) a+: Open the file in read-write mode (write at the end of the file content)
5. Read Files
a) Read specified characters
read()
file.read([size]) #File Opens the file for you with a custom name #[size] To specify the number of characters to read, if not written, read everything
Note: The read() method is used only if the mode specified is R (read-only) or r+ (read-write) when the file is opened.
Example:
with open('/mnt/file','r') as f: print(f.read(4)) #read the first 4 bytes #/mnt/file is: Life is short, I learn Python! Run result: Life is short
When a file is read using the read() method, it is read from the beginning of the file.Using the seek() method, you can move the file pointer to a new location and, when combined, read the contents of the file according to your needs.
seek()
File.seek (parameter 1, parameter 2) #Parameter Description #file: The name you customized when you opened the file #Parameter 1: Specifies the number of characters to move #Parameter 2: Specifies where to begin calculating the number of moving characters When # is 0, it means the calculation starts from the file header A # value of 1 indicates that the calculation starts at the current location A # value of 2 indicates that the calculation starts at the end of the file When parameter 2 is not written, default is 0
Note: If the rb mode is not used when opening a file, the relative position can only be calculated from the file header
Example:
with open('message.txt','r') as f: print(f.read()) f.seek(6) print(f.read(13)) Run result: Python is so powerful that you can't imagine it! Powerful, powerful beyond your imagination!
b) Read a line
readline(): Read one line at a time
Format:
file.readlline() #File: The name you customized when you opened the file
Note: You need to specify an open mode of R (read-only) or r+ (read-write)
Example:
with open('/mnt/fstab', 'r') as f: number = 0 while True: number += 1 #Line Number print(number, f.readline()) #Print the contents of each line if f.readline() == "": break #Break //Run result: 1 2 # /etc/fstab 3 # 4 # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info 5 UUID=9c23ef0d-02f7-41d3-adb4-662af3530361 / xfs defaults 0 0 6 UUID=186e4d32-33db-4d1b-9676-b3cce4261d57 swap swap defaults 0 0
3. Read all rows
readlines: Reads all rows and returns a list of strings, each containing an element
file.readlines() #File: The name you customized when you opened the file
Note: You need to specify an open mode of R (read-only) or r+ (read-write)
Example:
with open('/mnt/fstab', 'r') as f: print(f.readlines()) //Run result: ['\n', '#\n', '# /etc/fstab\n', '# Created by anaconda on Sun Mar 3 02:41:05 2019\n', '#\n', "# Accessible filesystems, by reference, are maintained under '/dev/disk'\n", '# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info\n', '#\n', 'UUID=9c23ef0d-02f7-41d3-adb4-662af3530361 / xfs defaults 0 0\n', 'UUID=fbbe7909-955c-48bb-823e-01d4a84f3f9a /boot xfs defaults 0 0\n', 'UUID=186e4d32-33db-4d1b-9676-b3cce4261d57 swap swap defaults 0 0\n']
When the file is large, the output of the contents of the file will be slow in this way and can be output line by line:
Example:
with open('/mnt/fstab', 'r') as f: for line in f.readlines() : print(line)
2. Directory operations (os module implementation)
Directories, also known as folders, are used to protect files hierarchically.
1. OS and os.path modules
Note: Different operating systems may produce different results!I take Linux as an example
Import os module
import os #After importing the OS module, you can also use its sub-module os.path
After importing the os module, the following variables are commonly used:
1) name: used to get the operating system type
import os print(os.name) Run result: If posix #indicates a Linux, Unix, or Mac OS operating system If nt #means Windows operating system
2) linesep: used to get line breaks on the current system
import os print(os.linesep)
3) sep: Used to get the path separator used by the current operating system
import os print(os.sep) Run result: /
2. Path
The string used to locate a file or directory is called a path.
1) Relative Path
Current directory: refers to the directory where the current file is located, viewed with os.getcwd()
import os print(os.getcwd()) #Output current directory Run result: /root/PycharmProjects/allen/Chapter 14 Files and IO
Relative Path = Absolute Path - Current Directory
2) Absolute Path
Absolute path refers to the actual path to a file specified when it is used
Format:
Os.path.abspath (relative path to obtain absolute path)
Example:
import os print(os.path.abspath('message.txt')) Run result: /root/PycharmProjects/allen/Chapter 14 Files and IO/message.txt
3) Stitching Path
If you want to stitch multiple paths together to form a new path, you can use the join() function
Format:
os.path.join(path1,path2,...,path n)
Note that using join() splicing does not detect whether a path really exists
Example:
import os print(os.path.join('/mnt','message.txt','dir')) //Run result: /mnt/message.txt/dir
3. Determine if the catalog exists
Format:
os.path.exists(dir_path) #dir_path is the directory or file to be determined, either relative or absolute #Existence returns True #No return False exists
Example:
import os print(os.path.exists('/mnt')) print(os.path.exists('/mnt/etc')) //Run result: True #existence False #Non-existent
Note: You can also determine if a file exists
4. Create a directory
1) Create a first-level directory
Format:
os.mkdir('dir_path') #dir_path is the directory or file to be created, either relative or absolute
Example:
import os os.mkdir('/mnt/etc') #Create etc directory under / mnt
After running:
2) Create a multilevel directory
Format:
os.makedirs('dir_path') #dir_path is the directory or file to be created, either relative or absolute
Example:
import os os.makedirs('/mnt/Class A/second level/Level 3')
After running:
5. Delete directory
rmdir(): Only empty directories can be deleted
Format:
os.rmdir('dir_path') #dir_path is the directory or file to be deleted, either relative or absolute
Example:
import os if os.path.exists('/mnt/etc') == True: #Determine if a directory exists os.rmdir('/mnt/etc') #Delete/mnt/etc directory else: print('/mnt/etc Non-existent!')
After running:
rmtree(): Non-empty directories can be deleted
import shutil #rmtree() function of shutil, a standard module built into Python shutil.rmtree('/mnt/Class A')
After running:
6. Traversing directories
Format:
os.walk(top='path') #path: Specifies the root directory of the content to be traversed #Return value: Returns a tuple generator object with three elements
Example:
import os tuple=os.walk(top='/home/allen') for i in tuple: print(i,"\n") Run partial results: ('/home/allen/.mozilla', ['extensions', 'plugins'], []) Return value: Element 1, Element 2, Element 3 Currently traversed path (string) Subdirectories (list) contained under current path Files contained under current path (list) ('/home/allen/.mozilla/extensions', [], []) ...
3. Advanced File Operations
1. Delete Files
os.remove(file_path) #file_path is the file to be deleted, either relative or absolute
Example:
import os os.remove('/mnt/file') #Delete/mnt/file file
After running:
2. Rename files and directories
Format:
os.rename(file_path_name1,file_path_name2) #file_path_name1: For files to be renamed, both relative and absolute paths are possible #file_path_name2: For files to be renamed, both relative and absolute paths are possible
Example:
import os name1='/mnt/fstab' name2='/mnt/fstab111' if os.path.exists(name1) == True: #Determine whether a file exists os.rename(name1,name2) #rename print(name1+'Renamed to'+name2) else: print(name1+'Non-existent!') //Run result: /mnt/fstab Renamed to/mnt/fstab111
Be careful:
The rename() function can also rename a directory, but it is the last directory name
3. Get basic information about files
The stat() function can obtain the following file information:
1) Last access time of file--st_atime
2) Last Modified Time---------------------st_mtime
3) File Size (in Bytes) ------------- st_size
4) Device Name--------------------------------------------------st_dev
5) User ID---------------------------------------st_uid
6) Group ID------------------------------------------------------st_gid
7) Hard Link Number (Number of Connected) -------st_nlink
8) Index number --------------------------------------------------------st_ino
Format:
os.stat(file_path) #file_path is the file for which information is to be obtained, either relative or absolute
Example:
import os if os.path.exists('/mnt/fstab111') == True: f=os.stat('/mnt/fstab111') print('/mnt/fstab111 Size is',f.st_size,'B') else: print('/mnt/fstab111 Non-existent!') //Run result: /mnt/fstab111 Size 501 B