- Home
- >
- Software Development
- >
- Saving Input to a File – InApps Technology 2022
Saving Input to a File – InApps Technology is an article under the topic Software Development Many of you are most interested in today !! Today, let’s InApps.net learn Saving Input to a File – InApps Technology in today’s post !
Read more about Saving Input to a File – InApps Technology at Wikipedia
You can find content about Saving Input to a File – InApps Technology from the Wikipedia website
So far in this introductory series to the Python programming language, we’ve learned some pretty cool basic Python tricks. We’ve learned what makes the language special, learned about the Python console and used variables, and learned how to accept input from users.
With that knowledge, we’ve created a couple of interesting little programs that illustrate how these features work in Python, but the applications themselves don’t do much outside of proving to your friends and family that you can learn a programming language.
This time around we’re going to create a program that uses much of what we’ve already learned adds some new bits and put it all together to create a program that can take input from a user and save it to a file. This can be handy if you want to keep track of a list of things but don’t always want to open the file to do so. Also, it’s an important trick for when you’re doing more advanced Python work. So this is similar to Algebra in high school… you will use it later in life.
Right?
Fine.
Anyway, let’s get on with the show.
Once again, I’ll be demonstrating this process on Linux. However, it will work on any operating system that supports Python. If, however, you’re working on a different OS, you might have to adjust here or there if things don’t work out as expected (they should though).
Write to a File
We’re going to take this one step at a time. The first thing you need to learn is how to write data to a file. To do this, we have to open a file (from within Python) in what’s called access mode. There are three different modes for this:
- Write only (w) – opens a file for writing.
- Write and Read (w+) – opens a file for both writing and reading.
- Append Only (a) – opens a file for writing. If the file doesn’t exist, it is created.
We’re going to focus on the write and append modes. First, the write mode. To do this we use the open()
function. Let’s say we want to write “Hello, New Stack” to a file called text.txt. First, create the file with:
touch text.txt
That file can now be written to with the write-only mode.
Create a new python script with:
nano write.py
The first thing we add to the file is the line to indicate we’re opening the text.txt file in write-only mode. That line will look like this:
file1 = open('text.txt', 'w')
Remember what variables are? What we’ve done here is define the variable file1 with the function that opens the text.txt file in write mode. We can then use that variable in the next two lines of the file.
The second line writes the string Hello, New Stack! to the file and looks like this:
file1.write("Hello, New Stack!")
The above line uses the same variable (file1), with a new function (write()
) to write the string to the file. The final line will close out the file and looks like this:
file1.close()
So our complete script looks like this:
#Open the text.txt file in write mode. file1 = open(‘text.txt’, ‘w’)
#Write the string “Hello, New Stack!” to the file file1.write(“Hello, New Stack!”)
#Close the file file1.close() |
Remember, everything that starts with a # character is a comment. We comment things so we know what’s going on in the code.
Save and close the file. Run the script with:
python3 write.py
If you view the contents of the text.txt file, you’ll see it contains the Hello, New Stack line at the top. If you run it again, the script will replace “Hello, New Stack” with “Hello, New Stack!” at the top. In other words, our script simply overwrites the first line in the text.txt file.
That’s all fine and good, but unless you only need to save a single line of text, it’s not very practical. That’s where the Append Only mode comes in handy. So let’s make a slight change. Instead of opening file1 in Write Only mode, we’ll open it in Append mode. That script looks almost identical to the first:
#Open the text.txt file in write mode. file1 = open(‘text.txt’, ‘a’)
#Write the string “Hello, New Stack!” to the file file1.write(“Hello, New Stack!”)
#Close the file file1.close() |
Spot the difference? I knew you would.
Now, if you run the python3 write.py command it’ll append Hello, New Stack! to the end of the first line. Run it a few times and you’ll end up with a file that looks like this:
Hello, New Stack!Hello, New Stack!Hello, New Stack!Hello, New Stack! |
Better, but still not ideal. What we want to do is create a script that will append the new line under the previous. To do that, we add the newline escape which is n
. So now our write()
function would look like this:
file1.write("Hello, New Stack! n")
If you run the script with that write() function a few times, the content of the text.txt file would look like this:
Hello, New Stack! Hello, New Stack! Hello, New Stack! |
Let’s now turn this into an actual application that will accept input from a user and write the input to a file. Remember, from our previous tutorial, this section:
print(“What is your first name?”) input1 = input() print(“What is your last name?”) input2 = input() |
We’re going to reuse it to ask a user their first and last name. Of course, to format this properly, we need to use a couple of tricks.
We’ve defined our variables for first name (input1) and last name (input2). Now we have to write them to the file in append mode with the line:
file1 = open('text.txt', 'a')
Next, we write the contents of the variables (by way of user input) and format it such that there’s a space between the first and last name and a new line return after the last name. If we don’t add those formatting options, our text file would wind up like:
JackWallenOliviaNightingaleWilJackson |
We don’t want that. What we want is:
Jack Wallen Olivia Nightingale Wil Jackson |
So that section looks like this:
file1.write(input1) file1.write(” “) file1.write(input2) file1.write(“n”) file1.close() |
As you can see, we’ve added the space between the names with file1.write(" ")
and the new line return with file1.write("n")
.
Our entire script now looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #Take input from user and assign it to variables print(“What is your first name?”) input1 = input() print(“What is your last name?”) input2 = input()
#Open the text.txt file for appending.
file1 = open(‘text.txt’, ‘a’)
#Write the content of the variables to the text.txt file file1.write(input1) file1.write(” “) file1.write(input2) file1.write(“n”)
#Close the text.txt file file1.close() |
When we now run python3 write.txt
a few times (entering different names) the script will write to the file exactly how we want.
And there you go! You’ve created a simple Python application that takes user input and writes it to a file. Get creative with this and see how many use cases you can apply this to.
Source: InApps.net
Let’s create the next big thing together!
Coming together is a beginning. Keeping together is progress. Working together is success.