Unraveling the Magic of File Input and Output in Python

Rushi PatelRushi Patel
9 min read

Have you ever wondered how your favorite programs remember your settings and files across different uses? It's all thanks to the fascinating concepts of file input and output. These magical processes enable data to be stored persistently and retrieved effortlessly, creating a seamless experience for users. In this blog, we'll explore the wonders of file input and output, and discover how various file types add an exciting twist to the story.

File Output - Saving Memories for the Future:

Picture your program's memory as a treasure trove of data. File output is like preserving precious memories by writing that data to a hard drive. However, not everything in memory needs to be stored. We only save what we'll need the next time we run the program. Think of it as capturing the current state of the program and locking it away in a file for safekeeping.

File Input - Unlocking the Stored Memories:

Now, imagine we want to access those memories again. File input is the key that unlocks the stored data and brings it back into the active memory. It's like reliving past experiences; the data that was previously outputted to the file magically reappears in the program, restoring it to its previous state. Ideally, the processes of file input and output are seamless companions, mirroring each other perfectly.

Decoding the Puzzle: The Magic of File Types:

In the digital world, files come in a myriad of types: PDFs, DOCs, JPEGs, PNGs, and countless others. Each file type follows a unique set of rules, like an ancient code that holds the data's secrets. When you open a file with a plain text reader, you may not see much information. That's because many files contain type-specific encoding that requires the right program to interpret them properly.

The Secret to Success: Understanding File Types:

A file type is like a set of rules for deciphering the data within. To correctly interpret a file, a program must know these rules. While you could learn each file type's secrets and create new programs to read them, it's much easier to leverage existing tools that handle the decoding for you.

Embrace the Magic of File Input and Output:

File input and output are the foundation of many incredible features in modern programs. Understanding the importance of file types allows us to build powerful applications that communicate effortlessly with users and other systems. In the next chapters of this blog, we'll delve into the practical side of things, teaching you how to open, write to, and save information in files using Python. Get ready to harness the magic of file input and output and take your Python programming skills to new heights! Stay tuned for the exciting adventure that lies ahead!

Now that we understand the enchanting world of file input and output, let's take a closer look at the captivating realm of plain text files. Here, three essential concepts take center stage: reading from files, writing to files, and appending to files. But before we dive into these enchanting acts, let's remember that every performance begins with the grand opening and concludes with a graceful closing.

The Opening Act: Opening Files with Care

In the wondrous land of Python, opening a file is a crucial first step. We assign the open file to a variable that acts as a gateway to its secrets. However, this act requires caution. If we attempt to open a file that doesn't exist, our program might throw an error and, worse, crash if the error isn't handled. That's why many programming languages, including Python, encourage us to enclose file input and output within a protective try block. This way, we gracefully handle any unexpected events and ensure our program doesn't come to an abrupt halt.

The Role of Modes: Specifying Your Intentions

In the realm of Python, opening a file involves stating our intentions. Are we seeking to read from it, write to it, or perhaps append new information to it? This is where file modes come into play. By specifying the mode when opening the file, we declare our purpose clearly. Whether it's read-only, write-only, or append mode, Python respects our desires and lets us interact with the file accordingly.

The Final Bow: Closing Files with Grace

As our performance comes to a close, we must remember the grand finale—the closing act. It's essential to inform the operating system that we're done with the file, allowing it to be accessed by other parts of the system once more. Closing the file gracefully ensures that all modifications are complete, and the file is ready to resume its role in the digital symphony.

This is how you can close a file....

outputFile.close() #closes the file

Now let's get to writing code

To open a file you can use the Python keyword open with the file name in parenthesis followed by the letter "w" if you are planning to write in the file, "r" if you are planning to read or "a" if you are planning to append.

#Initializing variables
number1 = 1 
number2 = 2
number3 = 3

#Saves the file as a variable ouputFile
outputFile = open("FileName.txt", w) # w means to write

#This will save the number variables as a string
outputFile.write(str(number1))
outputFile.write(str(number2))
outputFile.write(str(number3))
outputFile.write(str(4))

outputFile.close()

write() method works differently from the print() function you've been using so far. The write() method cannot take multiple arguments, and it does not automatically add a new line. There are several ways to add a new line.

#Example of adding new line in a file
write(number1 + "\n")

Well, that was variable.... What about lists? There are multiple way to do it for the lists

#Creating new list 
myList = ["Rushi", "5", 6.0, True, "File"]

#First way - Our classic for loop
for values in myList:
    outputFile.write(values + "\n")

#Second way - Using the python built in method "writelines" 
outputFile.writelines(myList) #Note this way will not add new line 
outputFile.write("\n".join(myList)) #This way will add the new line 

#Third way - Keyword parameters 
for values in myList:
    print(values, file = outputFile)

Adding a Playful Twist: Appending Items to a File in Python

Ah, file input and output—our magical tools for preserving data in the digital realm. But wait, there's a new trick up our sleeves! Welcome to the enchanting world of file appendage—where we add a dash of humor and a sprinkle of mischief to our files.

You might wonder, "Why on earth do we need to append anything? Can't we just write and be done with it?" Well, my curious friend, let me reveal the secret. When we use the "write" spell, it's like wielding a powerful eraser, obliterating everything in the file before scribing new content. Poof! The previous contents vanish into thin air! And that's no fun when you're trying to preserve valuable data, right?

Enter the marvelous "append" charm! This delightful incantation keeps the existing content intact and politely makes room for the newcomers at the end of the file. It's like inviting more guests to a party without kicking out the ones already having a good time. We call it the "party-extension" mode—making our files the hottest spots for data fun!

Now, picture this amusing scenario: Your file is like a treasure chest with all its precious items carefully stored. When you write, it's like emptying the chest and refilling it with new valuables. But with appendage, we sneakily add even more treasures, keeping the chest's original contents untouched. How cheeky!

To perform this enchanting feat, we use the "a" mode when opening the file, indicating our intention to append data. Once we've got our wand—err, I mean, our file—ready, we can cast the "write" spell as usual, and voilà! Our new data finds its place at the end of the file, ensuring nothing valuable is lost in the process.

So, next time you want to tinker with your files, remember the delightful art of file appendage. It's the perfect way to keep your old and new data partying together, like old friends sharing new jokes!

outputFile = open("FileName.txt", a) # a means to append

And the best part is that you can write items using the same way shown when writing something to a file.

Now, my fellow adventurers, it's time to unveil the art of reading from files! Just as we've learned to write and append to our files, we must now embrace the magic of extracting hidden treasures from within.

As we open the pages of our files, we'll discover a world of fascinating data, waiting to be revealed. The "read" spell is our trusty wand for this task, allowing us to uncover the secrets hidden within the text.

But beware, for not all files are alike. Some may contain numeric spells, while others hold strings of words waiting to be spoken. Our Python prowess will guide us as we interpret each file's unique language and extract the valuable information it holds.

So, gather your curiosity and let's embark on this thrilling journey of file reading! Once you master the art of reading from files, you'll be equipped with the knowledge to create powerful and dynamic programs that can interact with users and handle data like never before.

Prepare yourselves, dear readers, for the next chapter where we'll unravel the mysteries of reading from files, one enchanting line at a time! The magic of file input and output continues to unfold, and the adventure has only just begun! Onward we go, ready to seize the secrets of the files that await us!

inputFile = open("FileName.txt", "r") #Will read the file

#To read a line you can use the keyword readline
print(inputFile.readline().strip()) #This will read one individual line in order

#Strip will eliminate the white space that is there after a end of a line

Whenever you read from a file. It will always return the value as a string. So now you must be wondering what if I want the number instead of the number as a string. There is a solution for that as well. You can use the integer conversion function.

myInt = int(inputFile.readline())

You can also add all the Load the data from the file into a list

myList = [] #Initializes an empty list to append the data 

#iterates over the file and add the data to the list
for line in inputFile:
    myList.append(line.strip())

And there you have it, intrepid readers! We've journeyed through the captivating realm of file input and output in Python, unlocking its magical potential one step at a time. From writing and appending data, to revealing the secrets within, we've mastered the art of handling files with finesse.

I hope you've had as much fun as I did on this enchanting adventure. Through the ups and downs of file input and output, we've discovered the power of persistence and the wonders of file types. Together, we've learned how to read from files, write to them, and append new data—all the while sprinkling in a touch of humor along the way!

Hope you've learned something new and had a magical time on this adventure. Stay curious, keep coding, and let the wonders of Python never cease to amaze you! Farewell, until we meet again on our next quest! 🧙‍♂️✨

4
Subscribe to my newsletter

Read articles from Rushi Patel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rushi Patel
Rushi Patel