open file using ‘open mode’

We can open and read contents of a file in Python. File name can either be specified in the program itself or dynamically using sys.argv arguments. So first lets see how sys.argv works.

sys.argv contains argument vectors that a python interpretor takes while running a script. It contains list of all arguments being passed. By default sys.argv[0] is nothing but the script itself . Also to use this we first need to import the module sys.

Now lets us see how to open a file using file open method. The below example contains two examples one using hard coded filename and other using sys.argv.

Note that in the above code we read all the file contents into a list named lines. Now we print the contents of the file.

The full code for the above

import sys #note that sys module be loaded

#print(sys.argv) #uncomment this sentence to see what it prints
#sys.argv contains arguments in the form of list that the python program is been given while running 

#open file using open file mode
#fp = open('in.txt', "r", encoding='utf-8') # Open file on read mode and file name is hard coded
fp = open(sys.argv[1], "r" , encoding='utf-8') # Open file on read mode and file name is taken dynamically from arguments
lines ="\n") # Create a list containing all lines from the file
fp.close() # Close file

#read file line by line
for line in lines:
    print (line)    #this statement will print each line in the list

Start a Conversation

Your email address will not be published. Required fields are marked *