Files and I/O
Reading and writing text from a file is fairly simple in Python.
Opening
and Closing Files
3 modes for opening a file:
- read ("r")
- write ("w")
- append ("a")
Append mode is similar to write mode, except that
in append mode, any text that is written to the file is added to the
end of any pre-existing text in the file.
To open a file:
myFileVar =
open("myFileName", "theMode")
Example: To read from a file
"myData.txt"
inFile =
open("myData.txt", "r")
To close a file:
myFileVar.close()
In order to read from a file, it must exist and have its permissions
set so that it is readable.
Write vs. Append Mode:
If you open an existing file in write mode, any data in the file will
be over-written. If you want to preserve the original contents of the
file, use append mode instead.
Note: A file must be closed after you
are finished reading or writing.
Reading a File
A small file can be read all at once with the read() method:
inFile =
open("data.txt", "r")
fileContent =
inFile.read()
For files that are too large to be read all at once, read it line by
line with the method readline().
The readline() command will
read an entire line, including the newline character.
Example:
inFile =
open("input.txt", "r")
oneLine =
inFile.readline() # get first line in file
At any point, you can read the rest of the lines with the readlines() command, which returns a
list of strings, one string per line - remember that the newline
characters will be included in the strings.
If you want to read one line at a time from the file, you could also do
this:
inFile =
open("data.txt", "r")
for line in
inFile:
# do something with the line
inFile.close()
Exercise: Write a program that
opens a file for reading, and then for each line in the file, prints it
twice in uppercase to the screen. (Hint: import the string library and
use the string.upper() function).
Writing and Appending to a File
- Open the file in write or append mode
- write
mode - over-writes old content of file
- append
mode - adds new text to end of old file content
The write()
command adds text to a file. This method takes a string as its
parameter.
Note:
You must explicitly insert newline characters wherever you want a line
break.
Example:
outFile =
open("data2.txt", "w")
outFile.write("My
first line\n")
outFile.write("Some
more text")
outFile.write("And
still more")
outFile.close()
File data2.txt:
My first line
Some more textAnd still more
Exercise: Write a program that
writes the numbers 1 to 10, one per line, in a new file.
Remember: The write() command takes a string as its parameter.