There are a few things that can help you.
First, file_name is represented as a list of file names. It might be better called file_names , and then you can use file_name for each of them. You have confirmed that it has 5 entries.
The enumerate() function is used to enumerate a list of elements to provide both an index and an element for each cycle. This saves you from having to use a separate counter variable, for example.
for index, item in enumerate(["item1", "item2", "item3"]): print index, item
will print:
0 item1 1 item2 2 item3
This is not required since you decided to use the fileinput library. This is intended to take a list of files and iterate over all lines in all files in one cycle. Thus, you need to tweak your approach a little, considering that your list of files is called file_names , then you write something like this:
# Keep only files in the file list file_names = [file_name for file_name in file_names if os.path.isfile(file_name)] # Iterate all lines in all files for line in fileinput.input(file_names, inplace=1): if fileinput.filelineno() == 1: line = line.replace('Object','#Object') sys.stdout.write(line)
The main point here is that it is better to pre-filter any non-file names before transferring the list to fileinput . I will leave it for you to fix the exit.
fileinput provides a number of functions to help you determine which file or line number is currently being processed.
source share