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?
Assuming you're still having trouble, my typical approach is to open a file read-only, read its contents into a variable, close the file, make an
edited
variable, open the file to write (wiping out original file), and finally write theedited
contents.I like this approach since I can simply change the file_name that gets written out if I want to test my edits without wiping out the original file.
Also, I recommend naming containers using plural nouns, like @Martin Evans suggests.
Downside with this approach is that each file needs to be small enough to fit into memory twice (
lines
+out_lines
).Best of luck!