Tutorial Writing Files in Python

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Suppose we have test.txt file …

The following will open this file in “text” mode for “reading” …

Note that you explicitly have to call “close()” on the file.

A better equivalent way is to use the with block …

As indicated by the file.closed property being True, the file is automatically closed for you when it exits the with block.

The file.read() method reads the whole file. Instead, we can read line-by-line with readline() …

The if statement is to detect end of file. A blank line in the text file will not trigger this because it still has a “newline” character.

Or you can use readlines() which gives the whole file in a list of lines…

But perhaps the best way to read line by line is using a for loop …

So far, the file mode we have been using is “read” and “text”. Other modes includes …

r : read
t : text
b : binary
w : write (overwriting the entire file. Creates new file if not present)
a : writes to the end of the file (regardless of where cursor is). Creates new file if not present.

r+ : reads and writes starting cursor at 0 and overwriting characters. Will not create new file if not present.

You pass the file modes in the second argument of open(). Here is how you “write” in “text” mode …

If you want things on separate lines, use the \n.

The file object also has “seek()” method to move the cursor of where you will write next.


Related Posts

Tags

Share This