how to input multiple files in python script using sys.argv list

Viewed 1848

I want to take multiple files one by one into python script as input files and perform my script operations on all of those files one after another.I want to do this using sys.argv list but don't know how to do this properly. here is the piece of code I have:

import re
r=open('sys.argv[1]',"r")

What am I supposed to do first to initialize this list and then open them one by one to read by my script? Any help will be obliged. thanks

2 Answers

If you need to use them one by one from command, you may use sys.argv[1:]

import sys
    
def main():
    for filename in sys.argv[1:]:
        with open(filename, 'r') as file:
            file.readlines()
    
if __name__ == '__main__':
    main()

Something like this

import os,re
list1 = os.listdir()
for filename is list1:
  r=open(filename,"r")

Edit Another solution

import glob
list1 = glob.glob("*")
for filename in list1:
   r=open(filename,"r")
print(r)
Related