Python Input and Output

Python user input:

order = input(“Enter quantity to buy: “)

print(“You want to buy ” + order)

print(“at $10 each, that’s $” + str(int(order) * 10))

Check if file exists in Python (need to import os):

#!/usr/bin/env python3

import os

import sys

def main():

if os.path.exists(“example.txt”):

print(“example.txt exists”)


print(“no such file”)

if __name__ == ‘__main__’:



except KeyboardInterrupt:

print(“\nQuitting. Goodbye.”)


Reading from a file in Python:

Here is an example from my static site generator that displays the JSON fields in a .json file:

def read_article(project_object):



reading_choice = input(“Choose an article to read: “)

file_path = ‘projects/’ + project_object.get_project() + ‘/article_json/’ + reading_choice + ‘.json’

if reading_choice in open(‘projects/’ + project_object.get_project() + ‘/settings/articles.txt’).read()\

and os.path.isfile(file_path):

json_dict = {}

with open(file_path) as article_file:

json_dict = json.load(article_file)

print(“Title: ” + json_dict[“title”])

print(“Author: ” + json_dict[“author”])

print(“Date: ” + json_dict[“date”])

print(“First sentence: ” + json_dict[“first_sentence”])

print(“Body text: ” + json_dict[“body_text”])

print(“Lead image: ” + json_dict[“lead_image”])

print(“Article URL: ” + json_dict[“article_url”])


print(“Error: unable to find article ” + reading_choice)


Reading from a .txt file in Python (another example directly from one of my apps):

def show_all_articles(project_object):



number_of_articles = 0

with open(‘projects/’ + project_object.get_project() + ‘/settings/count.txt’, ‘r’) as count_file:

number_of_articles =

print(“there are {} articles in total:”.format(str(number_of_articles)))

with open(‘projects/’ + project_object.get_project() + ‘/settings/articles.txt’, ‘r’) as article_title_file:

for line in article_title_file.readlines():

if line != ‘\n’:



The above example shows opening a text file called count.txt, which only contains the number of articles on the website. It also opens a separate file called articles.txt, which is a list of all the article titles, each on a different line.

Every time a new article is created, the count.txt file is incremented and the articles.txt file gets the new article title.

Create a new file in Python, also from my SSG project:

def make_new_project(self, project_name):

if self.validate_name(project_name):

project_exists = os.path.isdir(“projects/” + project_name) # boolean

if project_exists:

print(“Error: project already exists.”)


return False


confirmation = input(“Are you sure you want to make a new project called ” + project_name + “? y / n: “)

if confirmation.lower() == ‘y’ or confirmation.lower() == ‘yes’:

print(“Creating new project called ” + project_name + “…”)


shutil.copytree(‘template’, ‘projects/’ + project_name)

except IOError:

print(“IOError encountered when trying to create project ” + project_name)


return True


print(“Did not end up making a project after all.”)


return False

That creates a new website project folder, and copies files from a template to the new project.

Here is a simpler file creation example though, only checking if a file already exists, and making it if it doesn’t:

if not os.path.exists(“example.txt”):

print(“you can make a file called example.txt”)

f = open(“example.txt”, “w”)

f.write(“here is the text in the file”)



print(“filename already exists, can’t proceed”)

Another good thing to do in the above example is add try/except for IOError, because there could potentially be IO issues, such as not having permission to write in that directory.

Writing over a file in Python:

Basically the same as before, but not checking if the file already exists:

f = open(“example.txt”, “w”)

f.write(“whatever used to be in this file will be gone now”)


Appending to a file in Python:

with open(“example.txt”, “a”) as myFile:

myFile.write(“this will be appended”)

For the open(filename, filemode) function, “a” means append, “w” means write, and “r” means read. If the file already exists, write mode will delete whatever was in it and replace it with the new stuff.

If you use “with open” instead of “file = open” then you can omit the final close() line.

A file can’t be used by anything else when it’s still open. It’s also good not to have lots of files open at the same time.

Deleting a file in Python (need to import os):

choice = input(“Really delete example.txt? y / n: “)

if choice == “y” and os.path.exists(“example.txt”):


When you write code that deletes stuff, it’s usually a good idea to ask the user to confirm that they really want to delete it. Data loss due to accidentally clicking a button or typing the wrong choice in a text prompt isn’t very fun. You also can’t delete a file that doesn’t exist, so you need to check that it exists first. Again, you can also do exception handling for IOError, because maybe you’re in a directory where you need elevated privileges in order to delete stuff, which would cause problems when trying to delete it as a normal user.

Something to consider about deleting a file is that you’re basically just freeing up the space on the hard drive or SSD to be written to again. In many cases, the OS doesn’t get rid of the 1s and 0s on it. All it does is remove the entry in the journaled file system which says that certain parts of the drive make up a certain file called example.txt.

If you really want to get rid of data, you will need to write random data on top of where the file used to be. Otherwise, the 1s and 0s that make up the file are still there, and file recovery software can recover it. It can be good to write random data over free space if you want to sell a hard drive or computer to someone on Craigslist, because you don’t want them to recover your personal documents and potentially steal your identity. But at the same time, you don’t want to write random data over free space all the time, because that would cause wear and tear on your drive, decreasing its lifespan. If you hear clicking noises on a hard drive, it’s called “the click of death” and means it’s not going to last much longer. It also takes a long time to write random data over free space as opposed to the quick and lazy OS deletion that still retains the data.

But just be aware that “deleting” a file rarely gets rid of it completely.

Files and important things can still be stored in RAM, suffering a similar problem to the persistent storage problem I just mentioned. For example, there was once a type of ransomware that would generate encryption keys, then encrypt a user’s data. Then it would demand that the user pay money via Bitcoin to get the keys to decrypt their files so that they can get them back. But the programmer of the ransomware was lazy, and the keys were still floating around in RAM, so someone developed a tool to find and retrieve them so that the files could be decrypted for free. It only worked if the computer wasn’t turned off though, because RAM resets when it gets powered off.

Additionally, operating systems will cache and log many things, so even deleting a file and writing random data over where it used to be won’t get rid of all the mentions of its existence. Among other things, this makes things more difficult for malware developers, as they can leave many different clues as to what they did and who they are.

If those kinds of topics interest you, I would encourage you to get into computer forensics, using tools such as AccessData FTK, which stands for Forensic Tool Kit. But if not, you can just get into general software development. Just know that there are tons of specializations. Not all software developers go down the same path. You might want to look into a topic called memory forensics. It can be useful for something called incident response, where a company gets hacked and you try to investigate and see what happened and who did it by seeing all the evidence they left behind, like malware, logs, recovering deleted files, things still floating around in RAM due to a lack of proper garbage collection, etc.

← Previous | Next →

Python Topic List

Main Topic List

Leave a Reply

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