Skip to main content
 Web开发网 » 编程语言 » Python语言

python-文件读与写详解1

2021年11月28日5970百度已收录

python-文件读与写详解1  python怎么读 第1张

文件内容a、yesterday

Oh, yesterday when I was young噢 昨日当我年少轻狂So many, many songs were waiting to be sung有那么那么多甜美的曲儿等我歌唱So many wild pleasures lay in store for me有那么多肆意的快乐等我享受And so much pain my eyes refused to see还有那么多痛苦 我的双眼却视而不见There are so many songs in me that won't be sung我有太多歌曲永远不会被唱起I feel the bitter taste of tears upon my tongue我尝到了舌尖泪水的苦涩滋味The time has come for me to pay for yesterday终于到了付出代价的时间 为了昨日When I was young当我年少轻狂b、打开文件

如果不使用encoding="utf-8",系统默认使用Windows的字符编码gbk打开。

而python的编码使用的是utf-8来打开文件。

data = open("yesterday",encoding="utf-8").read()

print(data)

运行结果:

Oh, yesterday when I was young噢 昨日当我年少轻狂So many, many songs were waiting to be sung有那么那么多甜美的曲儿等我歌唱So many wild pleasures lay in store for me有那么多肆意的快乐等我享受And so much pain my eyes refused to see还有那么多痛苦 我的双眼却视而不见There are so many songs in me that won't be sung我有太多歌曲永远不会被唱起I feel the bitter taste of tears upon my tongue我尝到了舌尖泪水的苦涩滋味The time has come for me to pay for yesterday终于到了付出代价的时间 为了昨日When I was young当我年少轻狂[Finished in 0.2s]c、给打印内容赋值,对文件对象进行操作

#文件句柄,就是文件的内存对象。

文件句柄包含文件名、字符集、大小,在硬盘上的起始位置

f = open("yesterday",encoding="utf-8") #文件句柄

data=f.read()

data2=f.read()

print(data)

print('----data----',data2)

运行结果:

Oh, yesterday when I was young噢 昨日当我年少轻狂So many, many songs were waiting to be sung有那么那么多甜美的曲儿等我歌唱So many wild pleasures lay in store for me有那么多肆意的快乐等我享受And so much pain my eyes refused to see还有那么多痛苦 我的双眼却视而不见There are so many songs in me that won't be sung我有太多歌曲永远不会被唱起I feel the bitter taste of tears upon my tongue我尝到了舌尖泪水的苦涩滋味The time has come for me to pay for yesterday终于到了付出代价的时间 为了昨日When I was young当我年少轻狂----data---- [Finished in 0.2s]如果是读2次,在第二次的时候是没有数据的,原因是:整个文件自上至下是一行一行的,第一遍读完的时候光标在最下面,在第二次的时候是空的。d、在文件中写内容

r:读模式w:写模式a:追加,append默认是读模式使用写模式后,会将原有文件内容冲掉,w模式是以写打开这个文件,并且创建一个文件,创建后就会将原有文件覆盖,使用时慎重使用w模式。f = open("yesterday","w"encoding="utf-8") #文件句柄

data=f.read()

print(data)

f.write("hello,world")

运行结果:

io.UnsupportedOperation: not writable[Finished in 0.4s with exit code 1]会报错:python中的文件需要制定,或者是读、或者是写,f = open("yesterday2","w",encoding="utf-8") #文件句柄

data=f.read()

print(data)

当使用w模式时,会创建一个新的文件。

python-文件读与写详解1  python怎么读 第2张

写内容

f = open("yesterday2","w",encoding="utf-8") #文件句柄f.write("hello,world\n")f.write("hello,world")运行结果:

python-文件读与写详解1  python怎么读 第3张

e、读写同时,追加

f = open("yesterday2","a",encoding="utf-8") #文件句柄

#a = append 追加

f.write("hello,world\n")

f.write("hello,world")

python-文件读与写详解1  python怎么读 第4张

python-文件读与写详解1  python怎么读 第5张

结语感谢阅读,欢迎在评论区中发表自己不同的观点,若有其他问题请在评论区留言,喜欢的朋友请多多关注转发支持一下。

头条号:ys0202

[---------END---------]

评论列表暂无评论
发表评论
微信