Menu
Home
Log in / Register
 
Home arrow Computer Science arrow Python Programming Fundamentals
< Prev   CONTENTS   Next >

3.7 Reading from and Writing to a File

A file is a grouping of related data that can be read by a computer program. Files may be stored in many different places including the hard drive, a thumb drive, on a CD, at a network location, really any place where a program could have access to it. While files occur in many forms and sizes, a text file is a bunch of text written using an editor and usually stored on a hard drive. Files can be read and written from Python programs. Files are another type of sequence as far as Python programs are concerned and we can iterate over them just as we would any sequence. Files are sequences of strings, one string for each line of the file. To read from a file we open it and then iterate over the lines of the file.

Example 3.12 A commonly used command in the Linux operating system iscalled cat which stands for catalog but actually prints the contents of a file tothe screen. We can write a similar program in Python. Here is the code. Forthis to work, you must enter the name of a file in the same directory or folder as the program that you are running.

1 filename = i n p u t ("Please enter the name of a file:")

2 catfile = open (filename ,"r")

3 f o r line i n catfile:

4 p r i n t (line)

5 catfile.close ()

Practice 3.14 If you run the program in Example 3.12 you will notice an extra blank line between the lines of the file. This is because there is a 'n' newline character at the end of each line read from the file. You can't see the newline character, but it is there. The print statement prints another newline at the end of each line. Modify the code in Example 3.12 to eliminate the extra line. Look at Chap. 10 for a method that will help you eliminate the extra newline character at the end of each line.

The program in Example 3.12 reads one line at a time from the file. The second line of the example opens the file for reading. To write a file it may be opened for writing by using a “w” instead of a “r”. You can also open a file with “a” for append to add to the end of an existing file.

Example 3.13 The program below writes to a file named by the user. The file is opened and it is closed. Closing is important when writing a file so you know when the file as been completely written. Otherwise, in some situations, the data may still be in memory and waiting to be written out. Closing the output file insures that the data has actually made it to the file.

1 filename = i n p u t ("Please enter the name of a file:")

2 yourName = i n p u t ("What is your name? ")

3 age = i n t ( i n p u t ("How old are you? "))

4 outfile = open (filename ,"w")

5 outfile.write("Hello "+ yourName +". How are you? ")

6 outfile.write("Next year you will be "+ s t r (age +1)

7 +" years old ")

8 outfile.close ()

When writing to a file you use the file.write method. Unlike the print function, you cannot write multiple items by separating them with commas. The write method takes only one argument, the string to write. To write multiple items to a line of a file, you must use string concatenation (i.e. the + operator) to concatenate the items together as was done in Example 3.13. When comma separated items in a print statement are

printed, a space character is automatically added between comma separated items. This is not true of string concatenation. If you want a space in the concatenated strings, you must add it yourself.

If you have non-string items to write to a file, they must be converted to strings using the str function. Otherwise, you'll get a run-time error when Python tries to concatenate a string to a non-string item. In Example 3.13 the age variable is an

integer because of the int conversion on the third line. In the sixth line, one is added to the age and then the sum age + 1 is converted to a string so it can be concatenated to the string literals and then written to the file.

 
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Philosophy
Political science
Psychology
Religion
Sociology
Travel