Step: Open File-"Action file-" close file
Open File
File handle = open (' File path ', ' mode ')
Specify file Encoding
File handle = open (' File path ', ' mode ', encoding= ' utf-8 ')
To prevent forgetting to close a file, you can use the context Manager to open the file
With open (' File path ', ' mode ') as file handle:
The mode of opening the file is:
R, read-only mode (default).
W, write-only mode. "unreadable; not exist; create; delete content;"
A, append mode. "Readable; not exist" create; "only append content;"
"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading
"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)
Close File
File handle. Close ()
Operation Files:
Detach
#占位
Fileno (return file descriptor for I/O operations of the underlying operating system)
FID = file handle. Fileno () print (FID)
Flush (Flushes the buffer, writes the data in the buffer immediately to the file)
File handle. Flush ()
Isatty (Determines whether the file is connected to an end device, returns a Boolean value)
File handle. Isatty ()
Read (reads the specified number of characters from the file and reads all by default)
str = file handle. Read () #读取整个文件str1 = file handle. Read (Ten) #读取文件前10个字符
Readable (determines whether the file is readable, returns a Boolean value)
File handle. Readable ()
ReadLine (reads up to one row at a time, with a newline character ' \ n ' at the end of each line)
Print (file handle. ReadLine ()) #读取第一行数据print (file handle. ReadLine (3)) #读取第二行前3个字符print (file handle. ReadLine ()) # Reads the remaining characters of the second line print (file handle. ReadLine ()) #读取第三行
Seek (move the pointer to read the file, if the file contains Chinese, move the pointer must be a multiple of 3, or it will be an error, because a Chinese character equals 3 bytes)
The file handle. Seek (6)
Seekable (determines whether the file pointer is available, returns a Boolean value)
File handle. seekable ()
Tell (get pointer position)
File handle. Tell ()
Truncate (truncate, delete the contents of the pointer and write to the file to operate in writable mode)
f = open (' Text.txt ', ' r+ ', encoding= ' Utf-8 ') F.seek (9) #把指针移动到第9个字节后面 (i.e. 3rd after Chinese) f.truncate () #把第3个中文后面的字符删除, and write to File F.close ()
Writable (determines whether the file is writable, returns a Boolean value)
File handle. Writable ()
Write (writes a string to the file and returns the number of characters)
File handle. Write (' string ')