内容搜索
hello.txt 文件为:
hello world
hello python
hello China
#文件查找
import re #引用re模块
f1 = open("hello.txt","r")
content = f1.read()
print("输出文件内容:\n",content) #输出文件内容
count = len(re.findall("hello",content))
#re.findall()返回的是一个列表
print("re.findall()的返回值: ",re.findall("hello",content))
print("共有{}个hello".format(count))
内容替换
f1 = open("hello.txt","r")
content = f1.read()
f1.close()
t = content.replace("hello","hi")
with open("hello.txt","w") as f2:
f2.write(t)
替换后文件内容为:
删除空行
# coding = utf-8
def clearBlankLine():
file1 = open('text1.txt', 'r', encoding='utf-8') # 要去掉空行的文件
file2 = open('text2.txt', 'w', encoding='utf-8') # 生成没有空行的文件
try:
for line in file1.readlines():
if line == '\n':
line = line.strip("\n")
file2.write(line)
finally:
file1.close()
file2.close()
if __name__ == '__main__':
clearBlankLine()