python基礎學習(十)

21.文件操做spa

 

 

# r只讀  w只寫(原來文件會消失!!!,也能夠建立新文件)  a追
# 加 r+ 讀寫
story_file = open("Story.txt", "r+")
#                     20讀取多長的字符串
# content1 = story_file.read()
# print(content1)
# readline() 讀取下一行
content2 = story_file.readline()
print("----------------1--------------------")
print(content2)
print("----------------2--------------------")
print(story_file.readline())
print("----------------3--------------------")
print(story_file.readline())
# readlines() 列表讀取
# ['冬眠結束後,小熊伸了一個很長的懶腰。\n', '他忽然看到樹洞門口堆滿了栗子。\n', '小熊撓了撓頭,「我不吃栗子啊。」\n', '不過他仍是很開心地笑了。']
content2 = story_file.readlines()
print("----------------4--------------------")
print(content2)
# print(content2[2])
print("----------------5--------------------")
# 迭代 列表讀取的內容  全部的字符串
for line in content2:
    print(line)

# 追加  a
story_file.write("\n第一行")
story_file.write("\n第二行")

story_file.close()

run結果:code

 

這是追加的:blog

 

相關文章
相關標籤/搜索