So we’ve already looked at what it takes to open a file for writing in Python, but how do actually send data to be saved, and then save that file? We’ll let’s take a look.
Let’s look at a simple program which will write three (3) names to a file.
def main() :
# get three names of people
name1 = input("Please enter a person's name: ")
name2 = input("Please enter a person's name: ")
name3 = input("Please enter a person's name: ")
# open the output file for writing. This will delete any existing data
outfile = open('names.txt', 'w')
# save the names into the file
outfile.write(name1 + '\n')
outfile.write(name2 + '\n')
outfile.write(name3 + '\n')
# close the file
outfile.close()
#call the main function
main()
First we get three names with the input function. Opening the file is simple. We are using the ‘w’ which opens the file for writing, and will overwrite any data that is in the file.
We use the write function to write the names. However, we want them to each be on their own line. Therefore we concatenate the name with a new line character – done by using \n.
Once the file has all the data we need, we can call the close function which saves the data in the file as it closes. This allows the data to be accessed by other people.
But what if you need to save some numbers into your file. Well, we’ve been working with text files, and means we need everything to be a string that we put into the file. Otherwise, Python will write binary data, which is a little more complex to work with, and cannot be read by another text application.
Luckily for us, there is a function which will convert your numeric data to string data: str(). You can almost think of it as the anti int() and float() function as it does the opposite. Where int() and float() take a string and convert it into a number, str() takes non-string data and converts it into a number.
Consider the following program:
import random
def main() :
# get three names of people
num1 = random.randint(1,200)
num2 = random.randint(1,200)
num3 = random.randint(1,200)
# open the output file for writing. This will delete any existing data
outfile = open('numbers.txt', 'w')
# save the names into the file
outfile.write(str(num1) + '\n')
outfile.write(str(num2) + '\n')
outfile.write(str(num3) + '\n')
# close the file
outfile.close()
#call the main function
main()
Writing Data to a File in Python was originally found on Access 2 Learn