Python allows you to view and create files, add, modify, and delete files, and the functions used are open in Python3.5.x, python 2.7.x supports both file and open, but file functions are removed from the 3.5.x series. Python file opening mode {... Python can view and create files, and can add, modify, and delete file content. the function used in Python3.5.x is
open
, Supported at the same time in Python2.7.x
file
And
open
But removed from the 3.5.x series.
file
Function.
Python file opening method
File Handle = open ('file path', 'open mode ')
Ps:The file handle is equivalent to the variable name. the file path can be either absolute or relative.
Python file opening mode
Basic mode
Mode |
Description |
Notes |
R |
Read-only mode |
File must exist |
W |
Write-only mode |
If the file does not exist, create the file. if the file exists, clear the file content. |
X |
Write-only mode |
The file cannot be read. if the file does not exist, it is created. if the file exists, an error is returned. |
A |
Append mode |
The file does not exist. if the file exists, add content to the end of the file. |
Tape+
.
Mode |
Description |
R + |
Read/Write |
W + |
Write and read |
X + |
Write and read |
A + |
Write and read |
Tapeb
.
Mode |
Description |
Rb |
Binary read mode |
Wb |
Binary write mode |
Xb |
Binary write-only mode |
AB |
Binary append mode |
Tip:When opened in the B mode, the read content is of the byte type, and the byte type also needs to be provided during writing.
Tape+
Tapeb
.
Mode |
Description |
Rb + |
Binary read/write mode |
Wb + |
Binary read/write mode |
Xb + |
Binary write-only mode |
AB + |
Binary read/write mode |
Python file reading method
Mode |
Description |
Read ([size]) |
Read all the content of the file. if the size is set, read the size byte for a long time. |
Readline ([size]) |
Read data from one row |
Readlines () |
Each row is read as an element in the list. |
The file name for the test ishello.tx"
, The file content is:
Hello Word!123abc456abc789abc
Read
Code:
# Open the file hello.txt f = open ("hello.txt", "r") in the read-only format # assign the value to the variable cc = f to read the file content. read () # close the file f. close () # print (c) the output value of c)
Output result:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.pyHello Word!123abc456abc789abc
Readline
Code:
# Open the file hello.txt f = open ("hello.txt", "r") in a read-only mode # read the first line c1 = f. readline () # read the second row c2 = f. readline () # read the third row c3 = f. readline () # close the file f. close () # print (c1) of the first row of output read file # print (c2) of the second row of output read file # print (c3) of output read file of the third row)
Output result:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.pyHello Word!123abc
Readlines
# Open the file hello.txt f = open ("hello.txt", "r") in the read-only format # assign all the file content to cc = f. readlines () # view the data type print (type (c) # close the file f. close () # traverse the output file content for n in c: print (n)
Result
C: \ Python35 \ python.exe F:/Python_code/sublime/Day06/file. py # output data type
Hello Word! 123abc456abc789abc
Python file writing method
Method |
Description |
Write (str) |
Write a string to a file |
Writelines (sequence or strings) |
Write multiple rows to a file. the parameter can be an iteratable object, list, and tuples. |
Write
Code:
# Open the write.txt file in a read-only mode. If no file is created, the file = open ("write.txt", "w") is overwritten. # write the test writefile string into the file content. write ("test write") # close the file. close ()
write.txt
File content:
test write
Writelines
Code:
# Open an existing wr_lines.txt f = open ("wr_lines.txt", "w", encoding = "UTF-8") in a read-only mode # write a list f. writelines (["11", "22", "33"]) # close the file f. close ()
wr_lines.txt
File content:
112233
Python file operations
Close (self ):
Close opened files
f.close()
Fileno (self ):
File descriptor
f = open("hello.txt","r")ret = f.fileno()f.close()print(ret)
Execution result:
3
Flush (self ):
Refresh the buffer content to the hard disk
f.flush()
Isatty (self ):
Checks whether the file is a tty device. if the file is a tty device, the system returnsTrue
Otherwise, returnFalse
f = open("hello.txt","r")ret = f.isatty()f.close()print(ret)
Returned results:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.pyFalse
Readable (self ):
Whether it is readable. if it is readableTrue
Otherwise, returnFalse
f = open("hello.txt","r")ret = f.readable()f.close()print(ret)
Returned results:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.pyTrue
Readline (self, limit =-1 ):
Read only one row of data at a time
f = open("hello.txt","r")print(f.readline())print(f.readline())f.close()
Returned results:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.pyHello Word!123
Readlines (self, hint =-1 ):
Treat each row as an element in the list.
f = open("hello.txt","r")print(f.readlines())f.close()
Returned results:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py['Hello Word!\n', '123\n', 'abc\n', '456\n', 'abc\n', '789\n', 'abc']
Get pointer position
f = open("hello.txt","r")print(f.tell())f.close()
Returned results:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py0
Seek (self, offset, whence = io. SEEK_SET ):
Specify the pointer position in the file
f = open("hello.txt","r")print(f.tell())f.seek(3)print(f.tell())f.close()
Execution result
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py03
Seekable (self ):
Whether the pointer is operable
f = open("hello.txt","r")print(f.seekable())f.close()
Execution result
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.pyTrue
Writable (self ):
Writable or not
f = open("hello.txt","r")print(f.writable())f.close()
Execution result
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.pyFalse
Writelines (self, lines ):
The string sequence of the written files, which can be produced by any iterative object string, usuallyString list
.
f = open("wr_lines.txt","w")f.writelines(["11","22","33"])f.close()
Execution result
112233
Read (self, n = None ):
Reads specified bytes of data. all data is read by default without parameters.
f = open("wr_lines.txt","r")print(f.read(3))f.seek(0)print(f.read())f.close()
Execution result
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py112112233
Write (self, s ):
Write content to the file
f = open("wr_lines.txt","w")f.write("abcabcabc")f.close()
File content
abcabcabc
Open multiple files at the same time
To avoid forgetting to close a file after it is opened, you can manage the context, that is:
With open ('log', 'r') as f: code block
In this way, when the with code block is executed, the file resources are automatically closed and released internally.
In Python 2.7 and later versions, with also supports managing the context of multiple files at the same time, namely:
with open('log1') as obj1, open('log2') as obj2: pass
For more articles about file operations in the full-stack Python series, refer to the PHP Chinese website!