1、创建文件:

    f = file('myfile.txt','w')    #myfile 为文件名,w为写权限。

    f .write("hello world!")    #hello world! 为要写入的文件的内容。

    f.close()                            #文件打开后一定要记得关闭,因为当有其他程序再次打开该文件的时候会报错。

    文件的权限还有:

    w+

    r+

    a+

    wb,rb二进制形式读写文件

eg1:实时写入

import time

f = file("f_test.txt",'w')

for i in range(15):

    time.sleep(1)    #休眠一秒

    f.write('The %s loops\n' % i)

    f.flush()        #每循环一次,讲内存中的数据写入到硬盘中,

time.sleep(10) #循环结束,休眠10秒

f.close()

 eg2:只有文件关闭或者程序结束之后,缓存在内存中的东西才能写入到磁盘中。

import time

f = file('f_test.txt','w')

for i in range(12):

    f.write('The %s loops \n % i)

time.sleep(10)

f.close()

 

 

import time

import fileinput

for line in fileinput.input('f_test.txt',inplace=1):

    line = line.replace('The 5 loops\n','Change me')

    print line