Reading and writing of text files

--Originally published at Programming Fundaments

In Python, you don’t need to import any library to read and write files., you just eed the flie to open, and for doing so, you will have to use the “open()” command:

file_object = open(filename, mode) #where file_object is the variable to put the
file object.

There are two types of files: text and binary; A text file is often structured as a sequence of lines and a line is a sequence of characters. And a binary file is basically any file that is not a text file. Binary files can only be processed by application that know about the file’s structure.

and you have to define a mode, which the are some type of:

  • ‘r’ when the file will only be read
  • ‘w’ for only writing (an existing file with the same name will be erased)
  • ‘a’ opens the file for appending; any data written to the file is automatically added to the end.
  • ‘r+’ opens the file for both reading and writing.

At the end it will create something like this:

>>> f = open('workfile', 'w')
>>> print f

To create an text file just follow the example:

file = open("newfile.txt", "w")

file.write("hello world in the new file
")

file.write("and another line
")

file.close()

Resulting in:

$ cat newfile.txt 
hello world in the new file
and another line

Examples and More at: http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python