Python入门知识点分享——(九)文件的input/output方法

首先对昨天介绍的open函数做一点补充,可以用with open的方式打开文件,这种方式可以省略close,防止资源泄露或数据丢失。这个方法依托的原理是上下文管理器,我们会在之后的文章中讲到。

with open('word_work.txt',  mode='r', encoding='UTF-8') as fp:
    print(fp.read())
  If we have chosen the position in life in which
we can most of all work for mankind, no burdens
can bow us down, because they are sacrifices 
for the benefit of all; then we shall experience
no petty, limited, selfish joy, but our happiness
will belong to millions, our deeds will live on
quietly but perpetually at work, and over our
ashes will be shed the hot tears of noble people.

我们可以使用fp.closed来判断文件是否被关闭,它会返回一个布尔值。另外我们也可以通过fp.name/mode读取open函数中的参数,这样可以避免我们不小心清空或覆盖了其他文件。

with open('word_work.txt',  mode='r', encoding='UTF-8') as fp:
    print(fp.name)
    print(fp.mode)
    print(fp.closed)
print(fp.closed)
word_work.txt
r
False
True

根据输出的结果,可以确认with open用法会自动关闭文件 。

下面是今天的重点——文件的 I/O 函数,其实我们刚刚介绍过的open函数,以及先前见过的print、close都属于文件的输入输出函数,这篇文章主要是进行归纳补充。 

print

最简单的输出方法是用print语句打印到屏幕,把输入的表达式转换成一个完整的字符串。

print("one", "two", "three", sep=" ")
# sep表示分隔符,可以是空格也可以是其他字符
print("one", "two", "three", sep="|")
print("name %s age %d" % ("alan", 11))
# %s作为字符串的占位符,而%d则是整型的占位符
name = "alan"
age = 11
print("name %s age %d" % (name, age))
# 用变量的形式也可以
one two three
one|two|three
name alan age 11
name alan age 11

input

input函数被用来读取键盘输入的文本,因为在Python中默认的标准输入是键盘。

question = input("请输入你的问题:")
print("你的问题是:", question)
请输入你的问题:你好吗
你的问题是: 你好吗

input函数常与print搭配形成交互,此外还可以使用split函数切分input返回的字符串从而得到一个列表。

question = input("请输入你的问题:")
print("你的问题是:", question, type(question))
print("你的问题是:", question.split(" "))
# 按照空格切分
请输入你的问题:1 2 3 4 5
你的问题是: 1 2 3 4 5 <class 'str'>
你的问题是: ['1', '2', '3', '4', '5']

close

文件的 close()方法会刷新缓冲区,并关闭该文件,这之后无法对该文件进行读写操作。

with open('word_work.txt',  mode='r', encoding='UTF-8') as fp:
      print(fp.readline())
print(fp.closed)
print(fp.name)
print(fp.mode)
print(fp.readline())
True
word_work.txt
r
ValueError: I/O operation on closed file.

 我们仍然能获取文件的一些属性,但是无法对里面的内容进行操作了。

write

write()方法可将任何字符串写入一个打开的文件,要在open函数中设置为可编写的形式。如果想要达成补充内容的效果,需配合seek定位函数使用。

fp = open('word_work2.txt',  mode='w+')
# 没有查找的该文件名,就会创建新文件并命名
fp.write("Karl")
fp.close()
fp = open('word_work2.txt',  mode='r')
print(fp.read())
fp.close()
fp = open('word_work2.txt',  mode='a+')
fp.seek(0, 2)
'''file.seek(offset[, whence])
offset:开始的偏移量,也就是代表需要移动偏移的字节数,如果是负数表示从倒数第几位开始。
whence:可选,默认值为 0。给 offset 定义一个参数,表示要从哪个位置开始偏移;0 代表从文件开头开始算起,1 代表从当前位置开始算起,2 代表从文件末尾算起。'''
fp.write("Marx")
fp.seek(0, 0)
# 指针移回开头
fp.close()
fp = open('word_work2.txt',  mode='r')
print(fp.read())
fp.close()
Karl
KarlMarx

read

read()方法从一个打开的文件中读取文本示例,输出的结果为字符串。

fp = open('word_work2.txt',  mode='r')
print(type(fp.read()))
fp.close()
<class 'str'>

tell

tell()方法输出文件内的当前位置,配合seek函数使用。

fp = open('word_work2.txt',  mode='r')
print(fp.tell())
fp.seek(0, 2)
print(fp.tell())
fp.seek(0, 0)
print(fp.tell())
fp.close()
0
8
0

再加上之前介绍的open函数就是文件全部的input/output方法了,之后会和大家分享OS的目录文件方法,谢谢大家。

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值