DEV Community

Cover image for Create a Simple Text Editor with Python
Shounak Das
Shounak Das

Posted on • Updated on

Create a Simple Text Editor with Python

In this post, I will show you a very easy way to create a simple text editor with Python. This tutorial is meant for absolute beginners. If you know the fundamentals of Python and a little bit of file handling, you can make one yourself. Before I begin, I would be explaining a bit of file handling for those who don't know anything about it.

File Handling

File handling is basically working with files using a programming language. You can open a file, read, write, delete data, and close it again, making permanent changes. Apart from these, there are many more operations, but we don't need to learn all those for this project. I will leave a link to a reference at the end of this post. You can visit it to learn more.

Opening and Closing a file

To open a file, we use the open() function. The open() function takes two parameters - file path, and mode.

There are four modes to open a file:

  • "r" - Read - Default value. Opens a file for reading. Produces an error if the file doesn't exist.
  • "a" - Append - Opens a file for appending, creates the file if it does not exist.
  • "w" - Write - Opens a file for writing, creates the file if it does not exist.
  • "x" - Create - Creates the specified file, returns an error if the file exists

In addition, you can specify if the file should be handled as binary or text mode.

  • "t" - Text - Default value. Text mode.
  • "b" - Binary - Binary mode (e.g. images).

Example:-

file = open("path/to/file.txt", "rb")
Enter fullscreen mode Exit fullscreen mode

Here, the mode "rb" tells python to "read the file in binary mode."

After you open a file and work on it, you need to close it. Python has the close() function that closes a file.

file = open("file.txt", "w")    # Opens a file in write mode
file.close()    # Closes the file
Enter fullscreen mode Exit fullscreen mode

Reading a File

The read() function allows us to read the contents of a file. It takes an optional argument (an integer) that specifies how many characters to read.

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

# Read all content and print
print(f.read()) 

# Read only 12 characters and print
print(f.read(12))
Enter fullscreen mode Exit fullscreen mode

Writing to files

Two modes allow us to write to files:

  • "a" - Append - will append to the end of the file
  • "w" - Write - will overwrite any existing content
f = open("file.txt", "a")
f.write("Now the file has more content!")
f.close()

f = open("file.txt", "w")
f.write("Whoops! I have deleted the content!")
f.close()
Enter fullscreen mode Exit fullscreen mode

That's enough file handling for now. Let's move on to the main part.


First, create a new python file. We will be using the path module from os. So, let's import it.

from os import path
Enter fullscreen mode Exit fullscreen mode

This will help us to check existing files. Now, we need the user to enter the path to the new or existing file. Let's store it in a variable file_path.

file_path = input("\nCreate file (please enter the path to file): ")
Enter fullscreen mode Exit fullscreen mode

Next, we need to check if the file already exists using the exists() function of the path module. For this, we need to write an if statement. The exists() function checks if the file already exists at the given path, in this case, file_path.

if path.exists(file_path):
    print("\n\tFile already exists!")
    ans = input("\nDo you want to use this file? (y/n)\n-> ")

else:
    print("\n\tCreating new file...\n")
    file = open(file_path, "a")
Enter fullscreen mode Exit fullscreen mode

If the file does not exist, then it will create a new file at the same location. Otherwise, it will ask if we wish to continue with the existing file. So, we need another if statement.

if ans == 'y' or ans == 'Y':
    file = open(file_path, "a")
    ans = input("\nDo you want to erase all content? (y/n)\n-> ")

else:
    exit()
Enter fullscreen mode Exit fullscreen mode

If we wish to continue with the existing file, it will ask if we wish to delete the content, or do we want to append text to it. Otherwise, the program will stop. So, let's write another if statement inside this one.

if ans == 'y' or ans == 'Y':
    print("\n\tErasing...\n")
    file.seek(0)
    file.truncate()

else:
    pass
Enter fullscreen mode Exit fullscreen mode

The pass keyword tells the compiler to just do nothing and move on to the next steps. Putting all parts together, your code should look something like this:

from os import path

file_path = input("\nCreate file (please enter the path to file): ")

if path.exists(file_path):
    print("\n\tFile already exists!")
    ans = input("\nDo you want to use this file? (y/n)\n-> ")

    if ans == 'y' or ans == 'Y':
        file = open(file_path, "a")
        ans = input("\nDo you want to erase all content? (y/n)\n-> ")

        if ans == 'y' or ans == 'Y':
            print("\n\tErasing...\n")
            file.seek(0)
            file.truncate()

        else:
            pass

    else:
        exit()

else:
    print("\n\tCreating new file...\n")
    file = open(file_path, "a")
Enter fullscreen mode Exit fullscreen mode

Now comes the most interesting part where we will build the interface. We need to inform the user how to use our text editor beforehand. So, paste this print statement.

print("\nPress RETURN to start a new line.\nPress Ctrl + C to save and close.\n\n")
Enter fullscreen mode Exit fullscreen mode

And now, paste these lines:

line_count = 1

while line_count > 0:
    try:
        line = input("\t" + str(line_count) + " ")
        file.write(line)
        file.write('\n')
        line_count += 1

    except KeyboardInterrupt:
        print("\n\n\tClosing...")
        break
Enter fullscreen mode Exit fullscreen mode

As you know, most text editors put a line number at the start of every line. Here, we will be doing something like that. I have used an infinite while loop so that you can add as many lines as you want to. But, we can't let it run forever. So, I have used a try/except statement, with the exception being raised by a KeyboardInterrupt, caused by pressing Ctrl + C.

If you don't know what the try/except statement is used for, in short words, it tries to run the code unless an exception (e.g. pressing a key, reaching the end of file, etc.) occurs.

Here, the line variable will store a single line of text, then it will write it to the file, add a new line, increment line_count by one, and again repeat unless you press Ctrl + C, which is used to stop a while loop (not to copy text).

Last but not the least, we need to close the file. Summing it up, your code will look like this:

from os import path

file_path = input("\nCreate file (please enter the path to file): ")

if path.exists(file_path):
    print("\n\tFile already exists!")
    ans = input("\nDo you want to use this file? (y/n)\n-> ")

    if ans == 'y' or ans == 'Y':
        file = open(file_path, "a")
        ans = input("\nDo you want to erase all content? (y/n)\n-> ")

        if ans == 'y' or ans == 'Y':
            print("\n\tErasing...\n")
            file.seek(0)
            file.truncate()

        else:
            pass

    else:
        exit()

else:
    print("\n\tCreating new file...\n")
    file = open(file_path, "a")

print("\nPress RETURN to start a new line.\nPress Ctrl + C to save and close.\n\n")

line_count = 1

while line_count > 0:
    try:
        line = input("\t" + str(line_count) + " ")
        file.write(line)
        file.write('\n')
        line_count += 1
    except KeyboardInterrupt:
        print("\n\n\tClosing...")
        break

file.close()
Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

Let's see the changes in the file abc.txt.

Alt Text

That's how our own text editor works and looks like. I hope today you learned something new and understand how you can apply your programming skills to create some cool projects. If you have any questions, just leave a comment and I will be happy to help you.

Happy Coding!😎


Resources

  • Python conditional statements πŸ‘‰ visit
  • Python while loops πŸ‘‰ visit
  • Python file handling πŸ‘‰ visit
  • Python os module πŸ‘‰ visit
  • Python try/except πŸ‘‰ visit

Top comments (3)

Collapse
 
coderninja123 profile image
CoderNinja123

Nice! Simplicity is the key. The same API can be used for higher-level text editors (e.g. VSCode in Python ;)

Collapse
 
snkds profile image
Shounak Das

Nowadays, with so many libraries and modules along with built-in functions, beginners can't learn how those functions actually work. So, it is always a wise decision to try to understand how those functions work and recreate them. If your foundation is strong, you can create everything from anything.πŸ‘

Collapse
 
coderninja123 profile image
CoderNinja123

Exactly! Plus, beginners don't use something like HALF the options available, as most of them are too complex.

Simplicity -> Productivity
That's one thing I learned πŸ˜€πŸ˜€

Some comments may only be visible to logged-in visitors. Sign in to view all comments.