15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

262<br />

Storing Data in Text Files<br />

Creating a text file typically requires three steps:<br />

1. Name a text file.<br />

2. Assign a variable to that text file.<br />

3. Store one or more lines of text in the text file.<br />

The following Python language example creates a text file named<br />

“mytext.txt” and stores the names Joe Smith, Mary Evans, and<br />

Donna Dickens in that file:<br />

names = “””Joe Smith<br />

Mary Evans<br />

Donna Dickens”””<br />

myfile = open(“mytext.txt”, “w”)<br />

myfile.write(names)<br />

myfile.close()<br />

The Python program follows these steps:<br />

1. This Python program stores the names Joe Smith, Mary Evans, and<br />

Donna Dickens in a names variable.<br />

2. This program creates (opens) a text file named “mytext.txt” and<br />

assigns this filename to a “myfile” variable.<br />

The “w” symbol tells the program to open the “mytext.txt” file so<br />

that you can write or add data to that text file.<br />

The “w” symbol tells the computer to erase everything inside the<br />

“mytext.txt” text file. If you want to add new data to a text file without<br />

erasing its entire contents, replace the “w” symbol with the “a”<br />

(append) symbol instead, like this:<br />

scraps = open(“mytext.txt”, “a”)<br />

scraps.write(“\nSal Lankins”)<br />

scraps.close()<br />

The preceding three lines of code would open the “mytext.txt”<br />

file, add a new line (the “\n” characters), and tack the name “Sal<br />

Lankins” at the end of the text file.<br />

3. The “myfile.write(names)” command tells the computer to take<br />

the data stored in the names variable and store (write) it in the text<br />

file assigned to the “myfile” variable.<br />

4. The “myfile.close()” command tells the computer to shut or close<br />

the file.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!