1, 读取
python常用的读取文件函数有三种read(), readline(), readlines()
1.1 read()
一次性读取文本中全部的内容, 以字符串的形式返回结果
with open('people.txt','r') as f:
data=f.read()
print(data)
huawei
alibaba
baidu
1.2 readline()
只读取文本第一行的内容,以字符串的形式返回结果
with open('people.txt','r') as f:
data=f.readline()
print(data)
huawei
1.3 readlines()
读取文本所有内容, 并且以数列的格式返回结果, 一般配合 for in 使用
with open('people.txt','r') as f:
data=f.readlines()
print(data)
for line in data:
print(line.strip('\n'))
['huawei\n', 'alibaba\n', 'baidu']
huawei
alibaba
baidu
2, 写入
2.1 存在则覆盖,不存在则创建
with open('people.txt','w') as f:
f.write('这是个测试!')
2.2 存在则报错,不存在则创建
with open('people.txt','x') as f:
f.write('这是个测试!')
2.3 存在则追加,不存在则创建
with open('people.txt','x') as f:
f.write('这是个测试!')
3, 读写模式
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.