Thursday, November 12, 2015

Reading a File with Python

Python's a pretty cool language. It's cross-system, you can complile the code to be an executable by bundling the files necessary to run the program together. Programs like "PyInstaller" help with this process.

It also has a pretty cool logo:
So, seeing how cool Python is (as i'm sure i've convinced you), check out this code for Python reading a file...

import sys
if __name__ == "__main__":
         # if len(sys.argv) > 1:
         if len("fileread.txt") > 1:
                 try:
                        #  f = open(sys.argv[1], "rb")
                        f = open("fileread.txt", "rb")
                 except:
                        # print "No file named %s exists!" % (sys.argv[1],)
                        print "No file named %s exists!" % ("fileread.txt",)
                 while 1:
                        t = f.readline()
                        if t == '':
                            break
                        if '\n' in t:
                            t = t[:-1]
                        if '\r' in t:
                            t = t[:-1]
                        sys.stdout.write(t + '\n')
                 f.close()

No comments:

Post a Comment