20201018-python文件操作

1、文件的打開,關(guān)閉及讀寫操作

打開:f=open(文件目錄、文件操作符) 、with open() as f

關(guān)閉:f.close()

讀寫:f=open("test.txt”,"r")、f=open(“test.txt",”w”)

2、有一個(gè)test.txt文件,以只讀的方式打開此文件,用變量f接收文件打開的返回值.

f=open(“test.txt”,"r")

3、文件訪問模式中r表示什么模式,r+表示什么模式?有什么區(qū)別?

r只讀 r+讀寫 文件指針都在文件開始的位置

4、文件訪問模式中w表示什么模式,w+表示什么模式?

w寫 w+讀寫

5、文件操作中要在文件中追加改如何操作?

open(“test.txt”,"a")

6、如何關(guān)閉一個(gè)文件?

使用file.close()語句

7、將打開的test.txt文件關(guān)閉,用變量f接收返回值.

f=close()返回值是None

8、請?jiān)趖est.txt文件中寫入"wow,so beautiful!".

f=open(“test.txt”,”w”)

f.write("wow,so beautiful!”)

f.close()

9、創(chuàng)建一個(gè)文件,把文件復(fù)制一遍——no

# 創(chuàng)建一個(gè)文件

with open("gailun.txt","w") as f:

? ? f.write("德瑪西亞,人在塔在")

# 把文件復(fù)制一遍

with open("gailun.txt","r",encoding='utf-8') as f:

? ? while True:

? ? ? ? index=f.name.find('.')

? ? ? ? # 獲取文件名

? ? ? ? file_name=f.name[:index]+'副本'+f.name[index:]

? ? ? ? # 讀取文件內(nèi)容

? ? ? ? content=f.readline()

? ? ? ? # 判斷文件是否讀完

? ? ? ? if len(content)==0:

? ? ? ? ? ? break

? ? ? ? else:

? ? ? ? ? ? # 寫入內(nèi)容

? ? ? ? ? ? wf=open(file_name,'w',encoding='utf-8')

? ? ? ? ? ? wf.write(content)

10、建立read.txt文件。

在此文件中寫入"hello world! hello python!hello everyone!"

打開文件,讀取5個(gè)字符。

查找當(dāng)前位置,并格式化輸出。

把指針重新定位到文件的開頭讀取10個(gè)字符串。

關(guān)閉文件

我的答案:

f=open("read.txt","w")

f.write("hello world! hello python!hello everyone!")

f.close()

f=open("read.txt","r")

content=f.read(5)

print(content)

print("當(dāng)前位置為:",f.tell())

f.seek(0,0)

print(f.read(10))

f.close()

官方答案:

f = open("read.txt","w")

f.write("hello python! hello everyone! hello world!")

f.close()

f = open("read.txt","r")

content = f.read(5)

print(content)

print("當(dāng)前位置為:",f.tell())

f.seek(10,0)

print(f.read())

f.close()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容