Python can view and create files, and can add, modify, and delete file contents. The functions used are open
in Python 3.5.x and in Python 2.7 .x supports both file
and open
, but the file
function was removed in the 3.5.x series.
文件句柄 = open('文件路径','打开模式')
Ps: The file handle is equivalent to the variable name, and the file path can be written as an absolute path or a relative path.
Basic mode
Mode | Description | Notes |
---|---|---|
r | Read-only mode | The file must exist |
w | Write-only mode | Create the file if the file does not exist, clear the file content if the file exists |
x | Write-only mode | The file is not readable. If the file does not exist, it will be created. If it exists, an error will be reported. |
a | Append mode | The file cannot be read. If the file exists, add the content at the end of the file |
Pattern with +
Mode | Description |
---|---|
Read and write | |
WRITE READ | |
WRITE READ | |
WRITE READ |
b
Description | |
---|---|
Binary read mode | |
Binary write mode | |
Binary write-only mode | |
Binary append mode |
WithTips: When opened in b mode, the content read is of byte type, and the byte type also needs to be provided when writing
+Pattern with
b
Description | |
---|---|
Binary read and write mode | |
Binary read and write mode | |
Binary write-only mode | |
Binary read-write mode |
Description | |
---|---|
Read the entire content of the file. If size is set, read size bytes for a long time | |
Read line by line | |
The content of each line read is used as an element in the list |
, and the file content is: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">Hello Word!
123
abc
456
abc
789
abc</pre><div class="contentsignin">Copy after login</div></div>
code :
# 以只读的方式打开文件hello.txt f = open("hello.txt","r") # 读取文件内容赋值给变量c c = f.read() # 关闭文件 f.close() # 输出c的值 print(c)
Output result:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py Hello Word! 123 abc 456 abc 789 abc
Code:
# 以只读模式打开文件hello.txt f = open("hello.txt","r") # 读取第一行 c1 = f.readline() # 读取第二行 c2 = f.readline() # 读取第三行 c3 = f.readline() # 关闭文件 f.close() # 输出读取文件第一行内容 print(c1) # 输出读取文件第二行内容 print(c2) # 输出读取文件第三行内容 print(c3)
Output result:
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py Hello Word! 123 abc
readlines
# 以只读的方式打开文件hello.txt
f = open("hello.txt","r")
# 将文件所有内容赋值给c
c = f.readlines()
# 查看数据类型
print(type(c))
# 关闭文件
f.close()
# 遍历输出文件内容
for n in c:
print(n)
C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py # 输出的数据类型 <class 'list'> Hello Word! 123 abc 456 abc 789 abc
Python file writing method
Description | |
---|---|
Write string to file | |
Write multiple lines to the file. The parameter can be an iterable object, list, tuple, etc. |