Friday, August 24, 2012

opening a file in python

I will use the sys (System-specific parameters and functions) module which is always available since its used or maintained by the interpreter.

To open a file use of sys.argv

sys.argv

the argv list contains the arguments passed to the script, when the interpreter was started. The first item contains the name of the script itself. (If the name of the script was used to start the program)  

I use terminal to start my programs and text-wrangler to write my programs.  Therefore to start the program open terminal and navigate to the folder where your program is saved.  

Next type $ python the_name_of_your_program the full address of your program

Example 

$ python test.py /Desktop/test.txt

Example script for opening and reading a file in python. 


from sys import argv

scriptName, fileName = argv

file = open(fileName)

# open(filename, mode) 'r' file will only be read,
# default is 'r' if the mode arguemnt is omitted
# 'w' for only writing.  Therefore an existing file with the same name will be
# erased.
# 'a' opens the file for appending, any data written to the file is automatically
# added to the end.
#'r+' opens the file for both rerading and writing.

print file.read()

# file.read(size) this read a quantity of data and
# and returns it as a string.  size is an optional numeric argument.
# However when the size is omitted or negative the entire contents of the file
# will open.  This could be very problematic if the file is twice as large as your
# machine's memory.