Python中文件的读写

文件的打开、读取、关闭:
在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文件夹里面的内容编程了我们写入的内容了。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值