對文件操作分:1、打開 2、讀/寫 3、保存文件
文件的讀寫三模式: 另記住:字符串大小寫操作中的capitalize() 和title()區別
w寫 w+讀寫: 有w的,原文件的內容就會先被清空
r讀 r+讀寫: 有r的,原文件必須存在(對於w那種方式,如果原文件不存在,則會重新創建)
a :在文件的末為添加內容
實例文件:2
1、此去經年,應是良辰好景虛設,
2、便縱有千種風情,更與何人說
練習:
1、循環讀取文件中的每一行
import os
fp = open('2','r+')
for line in fp:
print(line)
print(type(line))
fp.close()
若是用with open 打開:
with open ('2','r+') as fp:
for line in fp:
print(line)
print(type(line))
2、向文件中寫入內容
with open ('2','a+') as fp:
fp.write('寫入的內容‘)
3、用函數實現文件的讀取
def read_file(filename):
with open ('文件名','r+') as fp:
fp.seek(0)
content=fp.read()
print('content:',content)
read_file('2')
4、用函數寫文件
def write_file(filename,content):
with open('filename','a+') as fp:
fp.seek(0)
fp.truncate()
fp.write(str(content))
write_file('2','好好學習')