文件操作练习题

#想要读取一个文件的第三行
fp = open("e:\\a.txt","r",encoding="utf-8")
n=1
for  line in fp:  #fp是句柄,为可迭代对象,所以能用for循环
    if n==3:
        print(line)
    n+=1
fp.close()
 
 
升级小练习:请把它封装到一个函数里面
import os.path
 
 
def read_specific_line(file_path,line_number,encoding="utf-8"):
    if not os.path.exists(file_path):
        return None
    if not isinstance(line_number,int):
        return None
    content  = None
    fp = open(file_path,"r",encoding=encoding)
    n=1
    for line in fp:
        if n==line_number:
            content = line
        n+=1
    fp.close()
    return content
 
 
print(read_specific_line("e:\\a.txt",3,"utf-8"))
 
 
#健壮版:如果编码格式不对,用try...except...
import os.path

def read_specific_line(file_path,line_number,encoding="utf-8"):
    if not os.path.exists(file_path):
        return None
    if not isinstance(line_number,int):
        return None

    content  = None
    try:
        fp = open(file_path,"r",encoding=encoding)
        n=1
        for line in fp:
            if n==line_number:
                content = line
                fp.close()
                return content
            n+=1
        fp.close()     
    except:
        print("编码设定错误,请更换编码参数重试!")
        return content

print(read_specific_line("e:\\a.txt",3,"utf-8"))

 

转载于:https://www.cnblogs.com/wenm1128/p/11627988.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值