大爽Python入门教程 5-3 文件读写

大爽Python入门公开课教案 点击查看教程总目录

0 语法介绍

操作文件的固定语法如下

with open(file, mode) as f:
    ...

详细说明:

  • file是要操作的文件名,
  • mode是要操作的模式,
  • f是得到的文件对象名,也可以起其他名字,但是一般推荐起名f
  • ...是具体的处理代码,处于:后的缩进中。

1 读取文件

示例文件001.txt如下

math, 80
history, 70
chemistry, 75

读取代码如下
注:要保证代码和001.txt在同一文件夹下。

# 读取文件时,`mode`参数是`r`
with open("001.txt", "r") as f:
    print(f.readlines())

输出如下

['math, 80\n', 'history, 70\n', 'chemistry, 75']

其中\n是换行符。
print输出这个时会换行。

读取文件时,f支持的方法有

  • readlines: 得到所有行(字符串形式,带换行符)组成的列表
  • readline: 得到一行(字符串形式,(带换行符))
  • read: 得到所有文本组成的字符串(带换行符)
    使用这个读取001.txt,得到的是math, 80\nhistory, 70\nchemistry, 75

2 写文件

示例代码如下

# 修改文件时,`mode`参数是`w`
with open("002.txt", "w") as f:
    f.write("cat\n")
    f.write("bird\n")
    f.write("rabbit")

执行时,会(在代码文件夹下)生成002.txt如下

cat
bird
rabbit

写文件时,一般只使用fwrite方法。
该方法不会自动换行。
需要在里面的字符串手动写\n来换行。

3 老方法

with open(file, mode) as f:
    ...

with开头的这样一个语法,是比较新的语法。
在很多老的教程里面,可能用的是如下的两个语句:
(代码放在两句之间)

f = open(file, mode)
...
f.close()

其起到的功能和with open(file, mode) as f:是一样的。
这里更推荐使用with开头这样的写法。

4 其他模式

上文中介绍了mode,读r和写w的两种情况。

mode的值的基础情况如下

  • r: Opens a file for reading only.
    The file pointer is placed at the beginning of the file.
    This is the default mode.
    以只读方式打开文件。
    文件指针位于文件的开头。
    这是默认模式。
  • w: Opens a file for writing only.
    Overwrites the file if the file exists.
    If the file does not exist, creates a new file for writing.
    打开一个仅用于写入的文件。
    如果文件存在,则覆盖该文件。
    如果文件不存在,则创建一个新文件进行写入。
  • a: Opens a file for appending.
    The file pointer is at the end of the file if the file exists.
    That is, the file is in the append mode.
    If the file does not exist, it creates a new file for writing.
    如果文件存在,则文件指针位于文件末尾。
    也就是说,文件处于追加模式。(在文件末尾添加新内容)
    如果文件不存在,它会创建一个新文件用于写入。

以下内容较难,不需要掌握,简单了解即可
mode的值的拓展情况如下
注:以下值都是添加到rwa后面的

  • b: in binary format。
    使用二进制格式
  • +: for both appending and reading.
    既可以读,也可以写。(此时rwa的区别在于指针位置与是否覆盖)

两个值同时存在时,b在前,+在后

比如moderb+时,对应的意思为
Opens a file for both reading and writing in binary format.
The file pointer will be at the beginning of the file.
以二进制格式打开一个文件进行读写。
文件指针将位于文件的开头。

参考: confused-by-python-file-mode-w

posted @ 2021-11-23 18:15  大爽歌python编程辅导  阅读(69)  评论(0编辑  收藏  举报