Python @ DjangoSpin

Python: Manipulating Files

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Manipulating Files in Python

Manipulating Files in Python

The builtin open() function is used for opening files. This function returns a file object, which has methods like read() and write() associated with it, which are self-explanatory. When we are done manipulating the file, its close() method is called to close it.

# Contents of 'fileToBeReadFrom.txt'
Python is an extremely versatile language.
It is not limited to desktop applications or applications on the web.
People who code in Python are often referred to as "Pythonistas" or "Pythoneers ".
 
# readingFromAFile.py
# situated in the same directory as fileToBeReadFrom.txt
fileHandler = open('fileToBeReadFrom.txt')      # or open('fileToBeReadFrom.txt', 'r')
contents = fileHandler.read()
print(contents)
fileHandler.close()
 
# OUTPUT in Shell
# Run Menu > Run Module
Python is an extremely versatile language.
It is not limited to desktop applications or applications on the web.
People who code in Python are often referred to as "Pythonistas" or "Pythoneers".

To learn about File Manipulation in detail, I suggest you view this chapter of Python 101.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply