Starting up with Python – Part 16 – Last Part

Here we are with the last article "Starting up with Python". This one will shed some ideas on Working with files, Reading and Writing and Writing lines in Python. You can view all the past Python articles here.

python_logo_by_bluex_pl

39. Working with Files

To write to a file is pretty simple. I have the file toto which is blank at /python/toto. After using the close function the phrase hey hackers mauritius is written to toto.

>> fileop=open('/python/toto','w')
 >>> fileop.write('hey hackers mauritius')
 >>> fileop.close()

To read from the file do the following. The number 3 here means 3 byte

>> fileop=open('/python/toto','r')
 >>> fileop.read(3)
 'hey'

If you want to read the whole file, just put nothing inside the read function. Its important to close the function to prevent memory leaks.

>> fileop.read()
 ' hackers mauritius

40. Reading and Writing

Let's not read line by line. Here is how you read a whole line

>> fileop=open('/python/toto','r')
>>> print fileop.readline()
hey hackers mauritius

You can also read line by line and put it into a list

>> fileop=open('/python/toto','r')
>>> print fileop.readlines()
['hey hackers mauritius\n', 'how are you doing\n', 'what are the new projects?\n']

To create a new file or overwrite a file with some lines do this

>> fileop=open('/python/toto','w')
>>> fileop.write('This is a new LINE\n')
>>> fileop.close()

41. Writing Lines

Let's now create a list and store it into a temporary variable called listtest. listtest is now a list of all lines in toto.

>> fileop=open('/python/toto','r')
>>> listtest=fileop.readlines()
>>> listtest
['This is a new LINE\n']
>>> fileop.close()

We can also modify the same list. Here [1] is the second line as it starts with 0

>> filelist=open('/python/toto','r')
>>> listtest=filelist.readlines()
>>> listtest
['This is a new LINE\n', 'this is another line\n']
>>> filelist.close()
>>> listtest[1]="this is second line"
>>> listtest
['This is a new LINE\n', 'this is second line']

However, this has not been saved to the file. Let's see how to save it.

>> filelist=open('/python/toto','w')
>>> filelist.writelines(listtest)
>>> filelist.close()