Create a Simple Text Editor with Python
Tags: python, tutorial, beginners, youcandoit
Published: 2020-12-22 18:08:11

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:-*
```python
file = open("path/to/file.txt", "rb")
```
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.

```python
file = open("file.txt", "w")    # Opens a file in write mode
file.close()    # Closes the file
```

### 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.

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

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

# Read only 12 characters and print
print(f.read(12))
```

### 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

```python
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()
```

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.

```py
from os import path
```
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`.

```py
file_path = input("\nCreate file (please enter the path to file): ")
```
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`.

```py
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")
```

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.

```py
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()
```

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.

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

else:
    pass
```

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:

```py
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")
```

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.

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

And now, paste these lines:

```py
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
```

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 <kbd>Ctrl</kbd> + <kbd>C</kbd>.

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 <kbd>Ctrl</kbd> + <kbd>C</kbd>, 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:

```python
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()
```

### Output

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rcew5ircihtap5ma3jir.png)

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dhjtziz3emmihe3msp1q.png)

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](https://www.geeksforgeeks.org/python-if-else/)
* Python `while` loops 👉 [visit](https://www.geeksforgeeks.org/python-while-loops/?ref=lbp)
* Python file handling 👉 [visit](https://www.tutorialspoint.com/python/python_files_io.htm)
* Python `os` module 👉 [visit](https://www.geeksforgeeks.org/os-module-python-examples/)
* Python `try`/`except` 👉 [visit](https://www.geeksforgeeks.org/python-try-except/)