with open("time_and_location.txt", "r") as f: k=0 old="20180801002244172.000000_65.113129_-138.730759" for line in f.readlines(): k+=1 if(k>553863): line = line.strip('\n') old_location = old.split("_") get_time = line.split("_") if(get_time[2]!=old_location[2]): old=line insert_lightning(get_time[0],get_time[1],get_time[2]) print(k)
其中,r是只读模式,具体参数如下:
如需关闭,可以使用 f.close()。
以上是一次性读取整个记事本的示例,如果想单行读取的话,可以使用: f.readline()
上面是总体处理,接下来这段代码用来实现单个字符处理与替换:
import os f1 = open("test1.txt", "r") f2 = open("hupo1.txt", "r") f3 = open("caodi1.txt", "r") w1 = open("result1.txt", "w") for line in f1.readlines(): for one_char in line: if one_char=='1': re=f2.readline() re = re.strip('\n') w1.write(re) if one_char=='0': re=f3.readline() re = re.strip('\n') w1.write(re) if one_char!='0' and one_char!='1' : w1.write(one_char)