Read / Write

Here is how to open and read/write to a file within Python. Most languages supply a basic file opening and read/writing methods with the closing method, and Python is no different which makes going from one language to another very easy (you just need to learn the classes that are capable to doing the interesting stuff 🙂 ).

To write to a file, you have to open it first within a write mode (‘w’) and then write to that file *handler*, in the code below the variable ‘f’ is the file *handler*

f = open('write.txt','w');
f.write('hi there\n');
f.write('this is genux\n');
f.write('and my site is codingfriends.com\n');
f.write('pyhon does OO\n');
f.close();
print 'File has been written\n';

which will write to the “write.txt” the following text

hi there
this is genux
and my site is codingfriends.com
pyhon does OO

and then to read in the file you use the read mode ‘r’, you are able to use the Iterator style of coding with using a ‘for in :’ or if you wish to read one line at a time you can use the ‘readline()’ method, and to seek within a file you use the method ‘seek()’.

f = open('write.txt','r');
for readInLine in f:
	print readInLine;
 
print 'seek to the start of the file';
f.seek(0);
anotherLine = f.readline();
print anotherLine;
 
f.close();

and here is the output

hi there
 
this is genux
 
and my site is codingfriends.com
 
pyhon does OO
 
seek to the start of the file
hi there

Leave a Reply

Your email address will not be published.