Skip to main content
Engineering LibreTexts

10.10: Writing to Files

  • Page ID
  • To create a file, call the open() function pass it two arguments: a string for the name of the file, and the string 'w' to tell the open() function you want to open the file in "write" mode. The open() function returns a file object:

    >>> textFile = open('hello.txt', 'w')

    If you run this code from the interactive shell, the hello.txt file that this function creates will be created in the same folder that the python.exe program is in (on Windows, this will probably be C:\Python32). If the open() function is called from a .py program, the file is created in the same folder that the .py file is in.

    The "write" mode tells open() to create the file if it does not exist. If it does exist, then open() will delete that file and create a new, blank file. This is just like how an assignment statement can create a new variable, or overwrite the current value in an already existing variable. This can be somewhat dangerous. If you accidentally send a filename of an important file to the open() function with 'w' as the second parameter, it will be deleted. This could result in having to reinstall the operating system on your computer and/or the launching of nuclear missiles.

    The file object has a method called write() which can be used to write text to the file. Just pass it a string like you would pass a string to the print() function. The difference is that write() does not automatically add a newline character ('\n') to the end of the string. If you want to add a newline, you will have to include it in the string:

    >>> textFile = open('hello.txt', 'w')
    >>> textFile.write('This will be the content of the file.\nHello world!\n')

    To tell Python that you are done writing content to this file, you should call the close() method of the file object. (Although Python will automatically close any opened file objects when the program ends.)

    >>> textFile.close()