I'm looking for some help with my code which is rigth below :
for file in file_name :
if os.path.isfile(file):
for line_number, line in enumerate(fileinput.input(file, inplace=1)):
print file
os.system("pause")
if line_number ==1:
line = line.replace('Object','#Object')
sys.stdout.write(line)
I wanted to modify some previous extracted files in order to plot them with matplotlib. To do so, I remove some lines, comment some others.
My problem is the following :
Using
for line_number, line in enumerate(fileinput.input(file, inplace=1)):gives me only 4 out of 5 previous extracted files (when looking file_name list contains 5 references !)Using
for line_number, line in enumerate(file):gives me the 5 previous extracted file, BUT I don't know how to make modifications using the same file without creating another one...
Did you have an idea on this issue? Is this a normal issue?
There a number of things that might help you.
Firstly
file_nameappears to be a list of file names. It might be better namedfile_namesand then you could usefile_namefor each one. You have verified that this does hold 5 entries.The
enumerate()function is used to help when enumerating a list of items to provide both an index and the item for each loop. This saves you having to use a separate counter variable, e.g.would print:
This is not really required, as you have chosen to use the
fileinputlibrary. This is designed to take a list of files and iterate over all of the lines in all of the files in one single loop. As such you need to tweak your approach a bit, assuming your list of files is calledfile_namesthen you write something as follows:The main point here being that it is better to pre filter any non-filenames before passing the list to
fileinput. I will leave it up to you to fix the output.fileinputprovides a number of functions to help you figure out which file or line number is currently being processed.