Writing To A File Which Is Open In Read And Write Mode Altering The Structure
I have a text file, which has the following, contents: joe satriani is god steve vai is god steve morse is god steve lukather is god I wanted to write a code in python, which wil
Solution 1:
this is the solution if you want to write to the same file
file_lines = []
withopen('test.txt', 'r') as file:
for line in file.read().split('\n'):
file_lines.append(line+ ", absolutely man ..")
withopen('test.txt', 'w') as file:
for i in file_lines:
file.write(i+'\n')
this is the solution if you want to write into a different file
withopen('test.txt', 'r') as file:
for line in file.read().split('\n'):
withopen('test2.txt', 'a') as second_file:
second_file.write(line+ ", absolutely man ..\n")
Solution 2:
given_str = 'absolutely man ..'
text = ''.join([x[:-1]+given_str+x[-1] for x inopen('file.txt')])
withopen('file.txt', 'w') as file:
file.write(text)
Solution 3:
tried to write something with seek. you were just rewriting instead of inserting, so you'll have to copy the end of the file after writing your text
jj = open('readwrite.txt', 'r+')
data = jj.read()
r_ptr = 0
w_ptr = 0
append_text = " Absolutely ..man \n"
len_append = len(append_text)
for line in data.split("\n"): #to see what I am getting
r_ptr += len(line)+1
w_ptr += len(line)
jj.seek(w_ptr)
jj.write(append_text+data[r_ptr:])
w_ptr += len_append
Post a Comment for "Writing To A File Which Is Open In Read And Write Mode Altering The Structure"