python学习--文件操作

高效读文件:

f = open("ys",'r',encoding='utf-8')
count =0
for line in f:
    if count == 9:
        print("------woshi---")
        count += 1
        continue
    print(line.strip())
    count += 1
文件读写光标移动:
print(f.tell())#按字符个数来读
print(f.read(5))
print(f.tell())
结果:
0
Someh
5
返回到首行(开头):
print(f.seek(0))

打印进度条:

import  sys,time

for i in range(50):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.1)
修改文件(创建一个新的文件,旧的文件不作修改)

__author__ = "jelena"

f = open("ys2",'r',encoding="utf-8")
f_new =open("ys2.bak",'w',encoding="utf-8")

for line in f:
    if "肆意的快乐等我享受" in line:
        line = line.replace("肆意的快乐等我享受","肆意的快乐等jelena享受")
    f_new.write(line)
f.close()
f_new.close()

猜你喜欢

转载自blog.csdn.net/robert_hero/article/details/80864718