Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing in file's actual position in Python

Tags:

python

file

I want to read a line in a file and insert the new line ("\n") character in the n position on a line, so that a 9-character line, for instance, gets converted into three 3-character lines, like this:

"123456789" (before)
"123\n456\n789" (after)

I've tried with this:

f = open(file, "r+")
f.write("123456789")
f.seek(3, 0)
f.write("\n")
f.seek(0)
f.read()

-> '123\n56789'

I want it not to substitute the character in position n, but only to insert another ("\n") char in that position.

Any idea about how to do this? Thanks

like image 447
ramosg Avatar asked Oct 17 '25 18:10

ramosg


1 Answers

I don't think there is any way to do that in the way you are trying to: you would have to read in to the end of the file from the position you want to insert, then write your new character at the position you wish it to be, then write the original data back after it. This is the same way things would work in C or any language with a seek() type API.

Alternatively, read the file into a string, then use list methods to insert your data.

source_file = open("myfile", "r")
file_data = list(source_file.read())
source_file.close()
file_data.insert(position, data)
open("myfile", "wb").write(file_data)
like image 79
jkp Avatar answered Oct 20 '25 06:10

jkp