python笔记:文件操作
1、逐行打印整个文件
# -*- coding: utf-8 -*-
f = open("test",'r',encoding="utf-8") count = 0 for line in f: print(line.strip()) #strip忽略空格或换行符 count += 1
注意:
1)默认模式为r(读),w(覆盖),a(追加),r+(读写),w+(写读),a+(追加读写),rb(二进制文件);
2)strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。该方法只能删除开头或是结尾的字符,不能删除中间部分的字符;
使用with语句
会自动关闭文件。
# -*- coding: utf-8 -*- with open("test","r",encoding="utf-8") as f: for line in f: print(line.strip())
2、打印和移动光标
#打印光标
print(f.tell())
#移动光标
f.seek(10)
3、修改文件内容
# -*- coding: utf-8 -*- f = open("test","r",encoding="utf-8") f_new = open("test.tmp","w",encoding="utf-8") for line in f: if "你好呀" in line: line = line.replace("你好呀","您好啊") f_new.write(line) f.close() f_new.close()
新的文件test.tmp即为修改后的文件