您好,登錄后才能下訂單哦!
#文件的讀寫模式,r w x a b t +
def read_file():
text = 'test.text'
with open(text,encoding='utf-8') as r:#自動(dòng)關(guān)閉文件,可以使用完全路徑
rest = r.read()#將對(duì)象讀取成為文件
readline只讀一行
readlines讀取所有行 以列表形式出現(xiàn)
print(rest)
if name=='main':
read_file()
#文件的寫入
def write_file():#逐個(gè)寫入
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():#隨機(jī)記錄時(shí)間和用戶并且逐行寫入
rest = '用戶:{0} - 訪問(wèn)時(shí)間{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():#先讀再寫入 判斷是否有某個(gè)字符串
file_name = 'read_and_write' #這個(gè)需要先建立文件夾
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()
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。