Files

Files

Python allows you to work with the file system, which includes both files and directories. Using the built-in system functions, you can access, manipulate, open, read, write, append, and close files.

Opening a File

To open a file, use the open function. The first parameter is the path to the file, with the second being the mode.

Here is the list of modes:

  • r: Opens a file for reading.
  • a: Opens a file for appending.
  • w: Opens a file for writing.
  • x: Creates a new file.

Let's use the first one to open a file:

	
    file = open("file.txt", "r")
	

That's pretty much it. As long as the file exists, you have successfully opened a file in Python!

Reading a File

Now that you've opened a file, let's read from it. Use the read() function on the file:

	
    file = open("file.txt", "r")
    print(file.read())
	

Assuming the file contained this text:

	
    Hello!
    Welcome to sabe.io!
    Have fun!
	

That is exactly what you would see when you try to print it out. If you want to limit the number of characters returned back, give the length as the parameter, like so:

	
    file = open("file.txt", "r")
    print(file.read(6))
	
	
    Hello!
	

Read File Line by Line

Maybe instead of getting the entire file, you want to read it line by line. Thankfully, there is already a built-in function for this. The readline() function reads a file line by line each time. If you use it twice, the second time will return the second line.

	
    file = open("file.txt", "r")
    print(file.readline())
    print(file.readline())
	
	
    Hello!
    Welcome to sabe.io!
	

Alternatively, you can just loop over the lines, like so:

	
    file = open("file.txt", "r")
    for line in file:
        print(line)
	
	
    Hello!
    Welcome to sabe.io!
    Have fun!
	

Closing a File

Closing a file is important because it is sometimes needed to ensure any changes to a file are propagated in the file system.

This is how to close a file once you're finished with it:

	
    file = open("file.txt", "r")
    for line in file:
        print(line)

    file.close()
	

Our file is now closed!

Appending to Existing File

You can append text to an existing file pretty easily. Simply switch the mode when you open and use the write() function:

	
    file = open("file.txt", "a")
    file.write("Coding is fun!")
    file.close()

    file = open("file.txt", "r")
    print(file.read())
	
	
    Hello!
    Welcome to sabe.io!
    Have fun!
    Coding is fun!
	

Overwriting an Existing File

The only difference between appending and overwriting an existing file is the mode. Here is how you overwrite a file entirely:

	
    file = open("file.txt", "w")
    file.write("Coding is fun!")
    file.close()

    file = open("file.txt", "r")
    print(file.read())
	
	
    Coding is fun!
	

Creating new Empty Files

You can create a brand new file without any content in it by changing the mode to x:

	
    file = open("file.txt", "x")
    file.close()
	

A new blank file has been created!

Renaming a File

To rename a file using Python, we must import the os module, then use its rename() function.

Here's how that looks:

	
    import os

    os.rename("old_name.txt", "new_name.txt")
	

Pretty simple!

Deleting a File

Deleting a file also requires the use of the os module.

Here's how you do it:

	
    import os

    os.remove("file.txt")
	

Check if a File Exists

To avoid an error with trying to remove a file that does not exist, you should check if the file exists before trying to remove it.

This is how you do it:

	
    import os

    path = "file.txt"

    if os.path.exists(path):
        os.remove(path)
    else:
        print("This path does not exist: " + path)
	

Resources