#文件的讀寫模式,r w x a b t +
def read_file():
text = 'test.text'
with open(text,encoding='utf-8') as r:#自動關閉文件,可以使用完全路徑
rest = r.read()#將對象讀取成為文件
readline只讀一行
readlines讀取所有行 以列表形式出現(xiàn)
print(rest)
if name=='main':
read_file()
成都創(chuàng)新互聯(lián)公司主要從事網(wǎng)站設計制作、成都網(wǎng)站制作、網(wǎng)頁設計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務。立足成都服務西峽,10余年網(wǎng)站建設經(jīng)驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:13518219792
#文件的寫入
def write_file():#逐個寫入
file_name = 'test1'
f = open(file_name,'w')#以寫入的方式打開文件
f.write('hello')
f.write('\n')
f.write('world')
def write_mult_line():#一次性寫入
file_name = 'write_mult_line.txt'
with open(file_name,'w',encoding='utf-8') as f:
l = ['1','2','3']
f.writelines(l)
def write_user_log():#隨機記錄時間和用戶并且逐行寫入
rest = '用戶:{0} - 訪問時間{1}'.format(random.randint(1000,9999), datetime.now())
print(rest)
file_name = 'write_user_log.txt'
with open(file_name,'a',encoding='utf-8') as f:
f.write(rest)
f.write('\n')
def read_and_write():#先讀再寫入 判斷是否有某個字符串
file_name = 'read_and_write' #這個需要先建立文件夾
with open(file_name,'r+',encoding='utf-8') as f:
read_rest = f.read()
if '1' in read_rest:
f.write('kkkkkkkk')
else:
f.write('aaaa')
f.write('\n')
if __name__ == '__main__':
read_and_write()