Image of the glider from the Game of Life by John Conway
Skip to content

Python File Handling: Part I

Because learning a new language takes a little bit of time, I haven't had much to blog about here. I would like to blog more often, but I feel that I need to get a hang of the language before I can venture too far into blogging about it. I woudn't have much to blog about, and would just be wasting your time as a reader. However, I do also need to remember that while the focus is Perl, Python and PHP, I can also blog about Linux news and other geek related stuff. I guess it is just habit to put it on my other blog.

So, where to begin? How about file handling? Remember, I am working on converting QuickBasic files at work into Python files for all of our data manipulation and setup. This is something that I have taken on myself, and can only do when things are slow at work. This is one of those last priorities things when everuthing else is out of the way. So far, all I have been able to accomplish is successfully open a text file for reading, create a text file for writing, copy data from the read-only file, and paste it to the newly created file. Here is what I have so far:

fout = open('sample.fin', 'w')
fin = open('sample.txt', 'r')

while 1:
    line = fin.readline()   # Read line by line
    if not line:            # If EOF reached
        break               # exit program
    fout.writelines(line)   # write each line to new file

As you can see, it is all to plain, and not much is going on. The while loop will continue processing until we reach the EOF marker. When we do, exit the loop, thus also exiting the program. Not very exciting. Certainly, nothing advanced. I do find it odd, however, that most programming books wait until the middle chapters to cover file handling. Just an observation.

While this Python program does nothing but copy one file into another, it will grow as I get more time to work on it, and learn more about the language. Eventually, it will be advanced enough to replace the current QuickBasic program that we currently use. The QB program opens a file, looks at a certain row and column in that file, copies a certain length of text and pastes it to a specific location in the newly created file. While this sounds easy, in the QB program, there are actually several variables to take into account, and the text locations have to be exact. Also, the QB program is generated source code from another fairly large QB program, that will also be converted. Converting the larger QB program will take a great deal of time, due to the size of the source, and figuring out what everything does exactly.

Post a Comment

Your email is never published nor shared.