文件的打开、读取、关闭:
在Python中打开文件时我们会用到open()函数,使用格式为:
open(file,[mode,[buffering.[encoding] ] ]),其中的file参数时必选的其他的都是可选的。
其中file是指定文件的路径的。
mode 指定文件打开方式,例如:
‘r’ : 只读模式(mode的默认参数)
‘t’ :文本模式(mode的默认参数)
‘w’:写入模式,文件不存在会创建新的文件,存在就会覆盖原来的内容。
‘x’:创建与写入模式,如果文件已存在,将会报错。
‘a’:追加模式,在文件末尾追加写入内容。
‘b’:二进制模式,可以附加在其他模式后面。
‘+’:读写模式,可以附加在其他模式后面。
buffering 用于设置缓存,默认值为1(就是有缓存)
encoding 参数用于设置编码的方式,默认为None
我们在D盘 xu 文件下创建一个名为t的文本文件,我们读取里面的内容。
>>> r=open(r"D:\xu\t.txt")
>>> content=r.read()
>>> print(content)
hello python
hello c
hello java
>>>
我们在字符串前面加个 r可以避免路径中反斜杠等字符产生错误。
我们用read()方法读区其中的内容,然后打印出来其内容。
打开了文件我们不能忘记关闭它,这时候就用到了close()方法。例如下面的程序:
>>> r=open(r"D:\xu\t.txt")
>>> content=r.read()
>>> print(content)
hello python
hello c
hello java
>>> r.close()
>>>
我们为了避免忘记关闭文件,可以使用with open() as 变量: 这种结构,它可以实现文件的自动关闭,演示如下:
with open(r"D:\xu\t.txt") as r:
content = r.read()
print(content)
输出如下:
hello python
hello c
hello java
readline()可以逐行读取文件,演示如下:
with open(r"D:\xu\t.txt") as r:
content = r.readline()
print(content)
content = r.readline()
print(content)
输出如下:
hello python
hello c
readlines()方法把文件所有内容按行读取出来,每一行作为一个元素存储在列表中,演示如下:
with open(r"D:\xu\t.txt") as r:
content = r.readlines()
print(content)
输出如下:
['hello python\n', 'hello c\n', 'hello java']
写入文件内容:
使用write()方法可以写入内容,格式如下:
f.write(str)
str是要写入的字符串,这时候我们打开文件的时候mode参数就要为’w’.
‘w’:写入模式,文件不存在会创建新的文件,存的就是覆盖原来的内容。
演示如下:
tt="""hello python
hello python
hello c
hello java
hello xu
"""
with open(r"D:\xu\t.txt",'w',encoding='utf-8') as r:
r.write(tt)
with open(r"D:\xu\t.txt") as r:
content = r.read()
print(content)
输出如下
hello python
hello python
hello c
hello java
hello xu
可以看到t文件夹里面的内容编程了我们写入的内容了。