#author("2023-11-10T19:40:33+08:00","default:Admin","Admin") #author("2023-11-10T19:40:47+08:00","default:Admin","Admin") [[Python]] &color(red){※This article is based on Python 3.7.3}; #contents [[Python]] * 概要 [#sde989f3] import os * 读文件 [#y4b57090] ** read() 读取整个文件 [#p0177570] #codeprettify{{ f3=open('./test.txt', encoding='utf-8') contents1=f3.read() f3.close() }} ** readline() 每次读取一行文件 [#fbb2f5d1] readline() 每次读取一行文件,可利用循环将文件内容全部读出 #codeprettify{{ f4=open('./test.txt', encoding='utf-8') #此时只读取了一行 contents2=f4.readline() print(contents2) i=1 #利用循环全部读出 while contents2: print(f'第{i}行 {contents2}') contents2=f4.readline() i=i+1 f4.close() }} ** readlines() 读取文件的所有行 [#a95fcae1] readlines()方法读取整个文件所有行,保存在一个列表(list)变量中; #codeprettify{{ f5=open('./test.txt', encoding='utf-8') contents3=f5.readlines() f5.close() #打印第二行 print(contents3[1]) }} * 写文件 [#c7b6a592] 写进很多行 #codeprettify{{ with open('example.txt', 'w') as f: lines = ['Hello, world!', 'Welcome to Python'] f.writelines(lines) }} #hr(); コメント: #comment_kcaptcha