import os
def find(a):
mf4 = open("new3.txt",'w')
mf1 = open('words.txt','r')
for z in mf1:
if z[0:-1] == a: //z==a是匹配不出来的,因为每一行最后一个字符是‘\n’换行符
mf4.write(z)
mf1.close()
mf4.close()
if __name__ == '__main__':
os.chdir(r"C:\Users\Jia Zhong\Desktop")
mf1 = open('words.txt','r')
mf2 = open('new1.txt','w')
for x in mf1:
if len(x)>0 and x[0]=='a'://最好先确保这一行有值
mf2.write(x)
mf2.close()
mf1.close()//每一次打开f1遍历每一行,一定要关闭文件,不然一直定位在文件最后一行,你在去匹配,都是空字符串
mf3 = open('new2.txt','w')
mf1 = open('words.txt','r')
for y in mf1:
print(y[-2])
if len(y)>0 and y[-2]=='a':
mf3.write(y)
mf3.close()
mf1.close()
find('hello')
说明都写在注释里了