I have the following code to replace just one set of value from 26th line of 150 lines data. The problem is with the nested for loop. From the second iteration onwards, the inner loop isn't executing. Instead the loop skips to the last line
n= int(input("Enter the Number of values: "))
arr = []
print ('Enter the Fz values (in Newton): ')
for _ in range(n):
x=(input())
arr.append(x)
print ('Array: ', arr)
os.chdir ("D:\Work\python")
f = open("datanew.INP", "r+")
f1 = open("data.INP", "w+")
for i in range(len(arr)):
str2 = arr[i]
for j,line in enumerate(f):
if j == 25 :
new = line.split()
linenew = line.replace(new[1],str2)
print (linenew)
f1.write(linenew)
else:
f1.write(line)
print(arr[i], 'is replaced')
f.close()
f1.close()
The issue is that your code is looping over a file. On the first pass through, the end of file is reached. After that, there is no data left in the file to read, so the next loop has nothing to iterate over.
Instead, you might try reading over the whole file and storing the data in a list, then looping over that list. (Alternatively, you could eliminate the loops and access the 26th item directly.)
Here is some simple code to read from one file, replace the 26th line, and write to another file:
f = open("data.INP", "r") # Note that for simple reading you don't need the '+' added to the 'r'
the_data = f.readlines()
f.close()
the_data[25] = 'new data\n' # Remember that Python uses 0 indexing, thus the 25
f1 = open("updated_data.out", "w") # Assuming you want to write a new file, leave off the '+' here, as that indicates that you want to append to an existing file
for l in the_data:
f1.write(l)
f1.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With