自学python

                                            第五天

1.文件的打开操作

f = open("yesterday2",'r',encoding="utf-8")
print(f.tell())
print(f.readline())
print(f.tell())#输出字符数量
f.seek(0)#回到某个地方
print(f.readline())
print(f.encoding)
print(f.fileno())#返回文件的编号
print(f.readable())#判断文件是否可读
print(f.flush())#实时刷新,使write写的能够显示出来



import sys,time#导入的模块

for i in range(50):#字符串长度
    sys.stdout.write("@")#打印的样式
    sys.stdout.flush()#实时刷新
    time.sleep(0.1)#每个字符出现时间
#打印进度条

#f1 = open("yesterday2",'r+',encoding="utf-8")#文件读写
#f2 = open("yesterday2",'w+',encoding="utf-8")#文件写读
#f3 = open("yesterday2",'a+',encoding="utf-8")#追加写读
#f4 = open("yesterday2",'rb',encoding="utf-8")#二进制文件
#f4 = open("yesterday2",'rb')#读二进制文件
#f4 = open("yesterday2",'wb')#写二进制文件
#·f4.write("hello binary\n".encode())#最后记得关闭close

'''
r  只读模式(默认)
w  只写模式(不存在即创建,存在即删除后再写)
a  追加模式(可读,不存在则创建,存在则只追加内容)

r+  可读写文件
w+  写读
a+  同a

U表示在读取的时候,可以将\r\n  \r\n自动转换为\n
rU
r+U

b  表示处理二进制文件
rb
wb
ab

'''
yesterday2文件
Yesterday, all my troubles seemed so far away
昨天,所有的忧伤似乎都已走远,
Now it looks as though they're here to stay
但是现在他们仍然徘徊在我身边,
Oh, I believe in yesterday.
哦,我的昨天!

Suddenly, There's a shadow hanging over me.
突然间,天空变得黯淡。

I'm not half the man I used to be,
我已经不再是那个从前,
Oh, yesterday came suddenly.
哦,昨天啊,你来得太突然!

Why she had to go I don't know she wouldn't say.
我不知道她为何要走,她也从未明言。
I said something wrong, now I long for yesterday.
我一定说错了些什么,以致昨天让我如此留恋。

Yesterday, love was such an easy game to play.
昨天,爱情就像游戏一样贪玩,
Now I need a place to hide away.
现在,我需一个可以流泪的空间,
Oh, I believe in yesterday.
哦,我的昨天!

Why she had to go I don't know she wouldn't say.
我不知道她为何要走,她也从未明言。
I said something wrong, now I long for yesterday.
我一定说错了些什么,以致昨天让我如此留恋。

Yesterday, love was such an easy game to play.
昨天,爱情就像游戏一样贪玩,
Now I need a place to hide away.
现在,我需一个可以流泪的空间,
Oh, I believe in yesterday.
哦,我的昨天!

2.文件的修改

f = open("yesterday2","r",encoding="utf-8")

f_new = open("yesterday2.bak","w",encoding="utf-8")

for line in f:
    if "不再是那个" in line:
        line = line.replace("不再是那个","肆意的快乐等alex享受")
    f_new.write(line)
f.close()
f_new.close()
#实现创建一个新文件,并且修改文件中的字符
会自动创建出一个yesterday2.bak出来
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页