Python学习之文件操作

发布时间:2019-08-26 07:18:13编辑:auto阅读(1480)

    #/usr/bin/python
    
    content='''\                      #这里使用'''
    This is
    a test file
    for python
    '''
    f=file('content.txt','w')            #以写的方式打开content.txt,可以创建一个空文件
    f.write(content)                     #将content的内容写入到content.txt文件中
    f.close                              #关闭文件
    
    f=file('content.txt','r')            #以只读的方式打开文件
    line=f.read()                        #读出文件的内容
    print line,                          #print这里加了一个逗号,防止python读完最后一行后自动添加一行空行
    f.close()
    
    print "\n"
    
    f=file('content.txt')                 #默认以只读的方式打开
    while True:
          line=f.readline()               #读文件的每行内容
          if len(line)==0:                #如果一行的长度为0,表示读完了所有的行
             break                        #break跳出while循环
          print line,
    f.close()


    输出结果如下:

    This is
    a test file
    for python
    
    
    This is
    a test file
    for python


    python打开文件的方式可以为只读r , 写w,追加a。

    #/usr/bin/python
    
    content_append='''\
    Append more content
    into a file
    '''
    
    
    f=file('content.txt','a')           #向content.txt文件中追加内容
    f.write(content_append)
    f.close
    
    f=file('content.txt','r')
    line=f.read()
    print line,


    输出结果如下:

    This is
    a test file
    for python
    Append more content
    into a file


关键字

上一篇: python Function(函数)

下一篇: Python资料汇总