3

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

iqra khan
  • 45
  • 1
  • 6
  • 1
    @iqra.khan If any of the answers worked for please accept the answer and upvote the solution. – Manish Jul 20 '20 at 07:23

2 Answers2

3

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()
  • thanks, but this sys.argv[1:] is giving an empty list, on the same hand giving script.py name at 0 index (sys.argv[0]). I want it to read all files present in the same directory. – iqra khan Jul 12 '20 at 19:53
  • Also,i do not understand how to use this if statement? how to use this if statement or it is for what purpose? – iqra khan Jul 12 '20 at 19:55
  • @iqra khan, I thought you need to pass filenames as parameters in command. Something like this - `python script.py file1.txt, file2.txt, file3.txt....` As you need from the same directory use @Manish answer. If statement I used to run main function. You can read more [here](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Taras Struk Jul 13 '20 at 16:56
  • Thank you, i have initialized sys.argv with my file names starting from index 1 and it worked for me. – iqra khan Jul 17 '20 at 21:52
1

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)
Manish
  • 1,144
  • 8
  • 12
  • I have 17000+ files to read, but via this method only 9999 files are listed in list1 list. @Manish – iqra khan Jul 12 '20 at 18:59
  • 1
    @iqrakhan Are you sure if all fils are present in the same directory. I ran a sample test if the list takes 17k input and it does. list1 = [str(x) for x in range(1,17001,1)] print(len(list1)) # 17000 So that mean either listdir method is not working or files are not present ..... What have you investigated on it? – Manish Jul 13 '20 at 07:14
  • Length of the list is giving exactly the same number of my files, but when i tried to print the whole list, some file names are not printed. – iqra khan Jul 13 '20 at 08:42