Python files are the same as other files on your computer: documents, pictures, music, games . . . indeed, everything on your computer is stored as files.Let’s look at how to open and work with files in Python by using the built-in function open. But first we need to create a new file to play with.

Creating a Test File

We’ll experiment with a text file we’ll call test.txt. Follow the steps for the operating system you’re using.

Creating a New File in Windows

  1. Select Start ▸ All Programs ▸ Accessories ▸ Notepad.
  2. Enter a few lines into the empty file.
  3. Select File ▸ Save.
  4. When the dialog appears, select the C: drive by double-clicking My Computer and then double-clicking Local Disk (C:).
  5. Enter test.txt in the File name box at the bottom of the dialog.
  6. Finally, click the Save button.

Opening a File in Python

Python’s built-in open function opens a file in the Python shell and displays its contents. How you tell the function which file to open depends on your operating system. Look over the example for a Windows file.

Opening a Windows File

If you’re using Windows, enter the following code to open test.txt:

On the first line, we use open, which returns a file object with functions for working with files. The parameter we use with the open function is a string telling Python where to find the file. If you’re using Windows, you saved test.txt to the local disk on the C: drive, so you specify the location of your file as c:\\test.txt.

The two backslashes in the Windows filename tell Python that the backslash is just that, and not some sort of command.

Writing to Files

The file object returned by open has other functions besides read. We can create a new, empty file by using a second parameter, the string ‘w’, when we call the function:

The parameter ‘w’ tells Python that we want to write to the file object, rather than read from it.

We can now add information to this new file using the write function:

Finally, we need to tell Python when we’re finished writing to the file, using the close function:

Now, if you open the file with your text editor, you should see that it contains the text “What is green and loud? A froghorn!” Or, you can use Python to read it again:


3 thoughts on “Working with Files in Python

  1. “Wow, what an insightful article! I never thought about the topic from that perspective before. Thanks for sharing your thoughts and expertise!”

  2. This blog post really resonated with me. The examples you provided were spot on, and your writing style is engaging. Looking forward to reading more from you!

  3. “Thank you for shedding light on such an important topic. Your insights are thought-provoking and have given me a lot to reflect on. Keep up the great work!”

Leave a Reply

Your email address will not be published. Required fields are marked *