您好,登錄后才能下訂單哦!
python讀寫文件的方法?這個問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!
python怎么讀寫文件?
讀取操作
# 一次性讀取整個文件內(nèi)容 with open('致橡樹.txt', 'r', encoding='utf-8') as f: print(f.read()) # 通過for-in循環(huán)逐行讀取 with open('致橡樹.txt', mode='r') as f: for line in f: print(line, end='') time.sleep(0.5) print() # 讀取文件按行讀取到列表中 with open('致橡樹.txt') as f: lines = f.readlines() print(lines)
寫入操作
import csv class Teacher(object): def __init__(self, name, age, title): self.__name = name self.__age = age self.__title = title self.__index = -1 @property def name(self): return self.__name @property def age(self): return self.__age @property def title(self): return self.__title filename = 'teacher.csv' teachers = [Teacher('駱昊', 38, '叫獸'), Teacher('狄仁杰', 25, '磚家')] try: with open(filename, 'w') as f: writer = csv.writer(f) for teacher in teachers: writer.writerow([teacher.name, teacher.age, teacher.title]) except BaseException as e: print('無法寫入文件:', filename) else: print('保存數(shù)據(jù)完成!')
with open('prime.txt', 'w') as f: for num in range(2, 100): f.write(str(num) + '\n')
感謝各位的閱讀!看完上述內(nèi)容,你們對python讀寫文件的方法大概了解了嗎?希望文章內(nèi)容對大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。