Input and output of the complex IO operation, with synchronization (speed mismatch four etc.) and asynchronous (polling and message notification, complicated and efficient)
A file operation function:
File Open: F=open ("File path", "Operation type r/rb/w/a", "Encoding", "error Handling"),
File read/write: F.read/f.write/f.read (size)/f.readline ()/f.readlines ()
File closed: F.close
With statement: with Open function as F
F.read/wirte () #操作完自动关闭
Two memory operation IO:
Stringio:
>>> from IO import Stringio
>>> f = Stringio (' hello!\nhi!\ngoodbye! ')
Bytesio:
>>> from IO import Stringio
>>> f = Bytesio (b ' \xe4\xb8\xad\xe6\x96\x87 ')
>>> F.read ()
B ' \xe4\xb8\xad\xe6\x96\x87 '
Three: Operation files and directories: The OS module and the Shutil module provide the function of CopyFile () import OS, file path delimiter is/
3.1 Create folder Os.mkdir (; folder path ', ' folder name ') For example create under current folder: Os.mkdir ('./work '), delete folder Os.rmdir;
Switch the folder to a fixed path (you can import the relevant module only if you switch the working directory to the specified folder): Os.chdir ("C:\\users\\michael\\documents\\python\\mypython")
View current absolute path: Os.path.abspath ('. ')
- Os.chdir (".. /..") #表示上两级目录
- Os.chadir ("/") means switching to the root directory where the current file is located
3.2 Separating paths and files: Os.path.split (' folder path '), separating file name and type: Os.path.splitext (' Folder path ')
Set the path of the new file Os.path.join (' Folder path ', ' filename ')
3.3 Creating the file:
1) Os.mknod ("Test.txt") Create an empty file
2) Open ("Test.txt", W) opens a file directly and creates a file if the file does not exist
3.4 Copying Files:
Shutil.copyfile ("Oldfile", "NewFile") Oldfile and NewFile can only be files
Shutil.copy ("Oldfile", "NewFile") Oldfile can only be a folder, NewFile can 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
3.3 Files renamed and deleted, moved files (directories): Os.rename (' test.txt ', ' test.py '); Os.remove (' test.py '); Shutil.move ("Oldpos", "Newpos")
Judging the target
Os.path.exists ("goal") to determine if the target exists
Os.path.isdir ("goal") determine whether the target directory
Os.path.isfile ("goal") determine if the target is a file
Python Learning io: