python文件读取操作


def readfullfile(path:str):
    f=open(path,"r",encoding="utf-8")
    print(f"open对象类型{type(f)}")
    data=f.read()
    print(f"readfullfile读取文件内容{data}")
    f.close()

def readbylength(path:str,length:int):
    f=open(path,"r",encoding="utf-8")
    data=f.read(length)
    print(f"readbylength读取文件内容长度{length},内容为{data}")
    f.close()

def readlines(path:str):
    f=open(path,"r",encoding="utf-8")
    data=f.readlines()
    for line in data:
        print(f"readlines读取文件内容{line.strip()}")
    f.close()

print("=======================================")
fn="D:\\dev\\PyCharm\\works\\study\\base\\baseFileRead001.py"
readfullfile(fn)
print("=======================================")
readbylength(fn,100)
print("=======================================")
readlines(fn)
print("=======================================")
with open(fn,"r",encoding="utf-8") as f:
    lines=f.readlines()
    for line in lines:
        print(line.strip())

你可能感兴趣的:(python,开发语言)