Reputation: 57
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 will change the file lines like:
joe satriani is god ,absolutely man ..
steve vai is god,absolutely man ..
steve morse is god,absolutely man ..
steve lukather is god,absolutely man ..
I had tried doing such earlier once and I had not gotten the desired outcome. So, first I tried writing a code, which would just append "absolutely man" at the end of only the first line.
So, the following is my code:
jj = open('readwrite.txt', 'r+')
jj.seek(1)
n = jj.read()
print(" yiuiuiuoioio \n") #just for debugging
print(n)
f = n.split("\n" , n.count("\n")) #to see what I am getting
print(f) #As it turns out read returns the whole content as a string
print(len(f[0])) # just for debugging
jj.seek(len(f[0])) #take it to the end of first line
posy = jj.tell() # to see if it actually takes it
print(posy)
jj.write(" Absolutely ..man ")
But on executing the code, my file changes to the following:
joe satriani is god Absolutely ..man d
steve morse is god
steve lukather is god
The second line is being overwritten. How to append to one string at the end of one line?
I thought of opening the file in read and append mode but it would overwrite the existing file. I do not want to read strings from this file and write the into another file by appending. How to append or alter the lines of a file?
Is there any way to do it without any packages?
Upvotes: 1
Views: 452
Reputation: 1281
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
Upvotes: 0
Reputation: 164
given_str = 'absolutely man ..'
text = ''.join([x[:-1]+given_str+x[-1] for x in open('file.txt')])
with open('file.txt', 'w') as file:
file.write(text)
Upvotes: 1
Reputation: 2035
this is the solution if you want to write to the same file
file_lines = []
with open('test.txt', 'r') as file:
for line in file.read().split('\n'):
file_lines.append(line+ ", absolutely man ..")
with open('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
with open('test.txt', 'r') as file:
for line in file.read().split('\n'):
with open('test2.txt', 'a') as second_file:
second_file.write(line+ ", absolutely man ..\n")
Upvotes: 1