python讀寫文件的方法?這個問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!
創(chuàng)新互聯(lián)主營東阿網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都App制作,東阿h5重慶小程序開發(fā)公司搭建,東阿網(wǎng)站營銷推廣歡迎東阿等地區(qū)企業(yè)咨詢
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)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。