Though there are a lot of resources out there for Python,and great books, rarely do you find a simple reference guide that helps you navigate the basics. I found that there was not a lot of reference material to help you do the simple things, if you didn’t know what to look for.
This little guide will focus on the basics of reading and writing files in python..
First we are going to focus on reading from files. Open up your Python shell,
To open a file/file object :
- filename can be a file or path to a file
- mode can be any of the following
- ‘r’ for reading
- ‘r+’ for reading and writing
- ‘w’ for writing
- ‘a’ for appending
- both read and write modes also have a ‘b’ option for binary reading and writing (‘rb’, or ‘wb’)
myInput = open('myfile.txt','r')
This command will open the file “myfile.txt” in the current
directory, in “read” mode. You can access the methods of this file
using the ‘myInput’ variable. In the example, the open command will
open the file indicated in the first argument(‘myfile.txt’).
This argument can be a file, or the path to a file. The second
argument, is the file mode.
Once you have a file handle(myInput), you can work with that
file, depending on the mode you opened it with. We can now start
reading data from our file.
s = myFile.read() Will read entire file into a string
s = myFile.read(N) Will read N bytes (1 or more) from file
s = myFile.readline() Will read next line into string until end of line
L = myFile.readlines() Will read entire file into a list of strings