1, 读取

python常用的读取文件函数有三种read(), readline(), readlines()

1.1 read()

一次性读取文本中全部的内容, 以字符串的形式返回结果

  1. with open('people.txt','r') as f:
  2. data=f.read()
  3. print(data)
  1. huawei
  2. alibaba
  3. baidu

1.2 readline()

只读取文本第一行的内容,以字符串的形式返回结果

  1. with open('people.txt','r') as f:
  2. data=f.readline()
  3. print(data)
  1. huawei

1.3 readlines()

读取文本所有内容, 并且以数列的格式返回结果, 一般配合 for in 使用

  1. with open('people.txt','r') as f:
  2. data=f.readlines()
  3. print(data)
  4. for line in data:
  5. print(line.strip('\n'))
  1. ['huawei\n', 'alibaba\n', 'baidu']
  2. huawei
  3. alibaba
  4. baidu

2, 写入

2.1 存在则覆盖,不存在则创建

  1. with open('people.txt','w') as f:
  2. f.write('这是个测试!')

2.2 存在则报错,不存在则创建

  1. with open('people.txt','x') as f:
  2. f.write('这是个测试!')

2.3 存在则追加,不存在则创建

  1. with open('people.txt','x') as f:
  2. f.write('这是个测试!')

3, 读写模式

  1. ========= ===============================================================
  2. Character Meaning
  3. --------- ---------------------------------------------------------------
  4. 'r' open for reading (default)
  5. 'w' open for writing, truncating the file first
  6. 'x' create a new file and open it for writing
  7. 'a' open for writing, appending to the end of the file if it exists
  8. 'b' binary mode
  9. 't' text mode (default)
  10. '+' open a disk file for updating (reading and writing)
  11. 'U' universal newline mode (deprecated)
  12. ========= ===============================================================
  13. The default mode is 'rt' (open for reading text). For binary random
  14. access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  15. 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
  16. raises an `FileExistsError` if the file already exists.