Francais

Francais


Home


Products


Download


Tutorials

    Python Section
  • Python Quick Reference

  • Web Ring/Links


    Contact

    Files functions

    open()

    This function opens a file. The first parameter contains the path to access the file. The second contains the open's mode, r to read or w to write, in the last case, the file will be completely replace. Remark: the \ (backslash) is a special character, it must be doubled in file name or use in place the / (slash).

    Examples :
    open() to read open() to write
    >>>file=open("c:/test/file","r")
    >>>a=file.read()
    >>>file.close()
    >>>file=open("c:\\test\\file","w")
    >>>b=file.write("test")
    >>>file=close()

    close()

    This function closes a file opens previously by the open() function.
    Examples :see open().

    readline() readlines()

    Those functions read a file opens by the open() function. The first one, read a file line by line. The second assigns in a list variable all lines in the fine.

    Examples :
    readline() readlines()
    >>> file=open("c:/test/file","r")
    >>> var=file.readline()
    >>> file.close()
    >>> list=[]                # converts the sting in list
    >>> list.append(var) # to see it real content.
    >>> print var
    [ 'ligne1\n' ]
    >>> file=open("c:\\test\\file","r")
    >>> var=file.readlines()
    >>> file.close()
    >>> print var
    [ 'line1\n', 'line2\n', 'line3' ]

    write() writelines()

    Those functions write the variable's content in a file. The writelines() function writes into a file a list of lines, generally reads by the readlines() function, without add the carriage return at the end of line.

    Examples :
    write() writelines()
    >>> var="line"
    >>> file=open("c:/test/file","w")
    >>> file.write(var)
    >>> file.close()
    >>> list=[]
    >>> list.append("line1")
    >>> list.append("line2")
    >>> list.append("line3")
    >>>
    >>> index=0
    >>> while index<len(list):
    ... list[index]=list[index]+"\n"
    ... index+=1
    ...
    >>> file=open("c:\\test\\file","w")
    >>> file.writelines(list)
    >>> file.close()

    flush()

    This function forces the writing data still pending in I/O buffer. This function is implicitly calls by the close() function. Generally, this function is used to create a journal file that allows a program to restart at it last control point written.

    Example :
    flush()
    >>> var="line"
    >>> file=open("c:/test/file","w")
    >>> file.write(var)
    >>> file.flush()
    >>> file.close()

    Credit

    Author and translation : Guy Demesmaeker
    © Sabam 2004



    Previous Page
    13/13