• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
python读写TXT指定参数

 

 

 

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime  #时间

time_begin="8:00"
time_over ="22:00"

#函数名 读取txt中指定参数内容
#函数输入
# path_txt  txt文件地址
# canshu    要从txt读取的内容
# fengefu   参数名字和值的分隔符号 默认 -
#函数输出
# 返回字符型结果

def readtxt(path_txt,canshu):
    #/home/pi/Desktop/info
    fengefu="-"
    f = open(path_txt, mode='r+', encoding='utf-8')  # 打开txt文件,以‘utf-8’编码读取
    lines = f.readlines()   # 以行的形式进行读取文件
     
    for line in lines:
        a=line.strip().split(fengefu)    # x.strip()#除去每行的换行符 按照:分割
        b = a[0:1] # list--str
        c = "".join(b).strip()  # 去除空格
        
        if  c==canshu:
            b = a[1:2]   # 这是选取需要读取的位数
            c="".join(b).strip()  # 去除空格   
            #print(c)
            return c
    f.close()
    

def main():
    #读取开始时间 字符型 数字需要转化 int()
    time_begin=readtxt("/home/pi/Work/WorkPlace/python/2waibao/2face_lab/info","time_begin")
    print(time_begin)
    #读取结束时间
    time_over=readtxt("/home/pi/Work/WorkPlace/python/2waibao/2face_lab/info","time_over")
    print(time_over)
    #获取当前和时间
    now = datetime.datetime.now().strftime("%H:%M")
    print("当前时间:" + now)
    #比较是否在时间段内
    if time_begin < now < time_over:
        print("在此区间中")
    else:
        print("不在此区间中")


main()

  

其他使用

    #统计行数
    def counttxt(self,path_txt):
        fp = open(path_txt, mode='r+', encoding='utf-8')
        liness = fp.readlines()
        
        num=0
        for line in liness: 
            num +=1
        fp.close()   
        print(num)
        return num
        
    #指定行写入一行
    def write_linetxt(self,path_txt,canshu):  
        fp = open(path_txt, mode='r+', encoding='utf-8')
        liness = fp.readlines()
        lines = []
        for line in liness: 
            lines.append(line)
        fp.close()   
        print(len(lines))    
        lines.insert(0, canshu+"\n") # 在第二行插入       
        fp = open(path_txt, mode='w+', encoding='utf-8')  
        for line in lines:    
            fp.writelines(line)
        fp.close()
    #最后一行插入一行
    def writetxt(self,path_txt,canshu):  
        fp = open(path_txt, mode='a', encoding='utf-8')
        fp.write("\n"+canshu)
        fp.close()

  

 

posted on 2020-01-05 03:31  MKT-porter  阅读(476)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3