Skip to content Skip to sidebar Skip to footer

Writing In File's Actual Position In Python

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-characte

Solution 1:

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)

Solution 2:

with open(file, 'r+') as f:
    data = f.read()
    f.seek(0)

    for i in range(len(data)): # could also use 'for i, chara in enumerate(data):' and then 'f.write(chara)' instead of 'f.write(data[i])'if (i + 1) % 3 == 0:  # could also do'if i % 3 == 2:', but that may be slightly confusing
            f.write('\n')
        else:
            f.write(data[i])

I don't think it's all that Pythonic (due to the range(len(data))), but it should work, unless your data file is really really large (in which case you'll have to process the data in the file part by part and store the results in another file to prevent overwriting data you haven't processed yet).

(More on the with statement.)

Solution 3:

You can think a file is just an array of characters, and if you want to insert a new element in the middle of an array, then you have to shift all the elements that are after it.

You could do what you say if the file contained a "linked list" of chars or "extends", but then you would need a special editor to see it sequentially.

Post a Comment for "Writing In File's Actual Position In Python"