Base Nordwind

"7.81% more interesting than the news"

Home     Programming     About      
Creating a simple file utility in Python
 
Python makes it very easy to read/write files. In order to avoid constantly re-writing this common code, we will package it into a small utility that can be imported into any of your projects by including the file and using the "import fileName" command.
There are three main functions that we will want to provide: creating/overwriting a file, appending a file that already exists, and reading a file. It is generally implied that we will be writing a list of strings to the file (  ['item1","item2"...]  ), however any standard object can be used.
 
-writeFile-
This function takes "file" and "contents" as arguments. "file" is generally a string such as "example1.txt". "contents" can be anything, but it is best interepreted as a list of strings, such as " ["bad","smelly","kitty"] "
The "\n" command is appended to each line to make sure that the file is written out as individual lines instead of one long line.
Please note that this function will overwrite "file" if it already exists.
 
-returnListFromFile-
 This function basically does the opposite of writeFile. It reads a file line by line, and stores the results in a list, which it then returns to the caller of the function.
 
-appendFile-
This fuction is used when you don't want to overwrite a pre-existing file. It reads the contents of the pre-existing file, adds the new data, and then overwrites the file with sum of the old and new data.
 
 
To use this code, simply type it into a text document, and save it with a .py instead of .txt
To reference this code from another file, use the import command: import filename  (leave off the .py extension)
Then call the methods like so:
----------------------------------------------------
import fileUtility
 
fileUtility.writeFile("example.txt",["For the Salt!","How do you spell Pythagreon?"])
----------------------------------------------------
 
Note: This works best when both code files are in the same folder