0

I want to insert my Random()'s return value into txt file without overwrite ('a') and to a specific location, like at the sixt character, but when I execute this, Random is insert to the third line.

`def Modif_Files(p_folder_path):

    Tab = []
    for v_root, v_dir, v_files in os.walk(p_folder_path):
        print v_files
        for v_file in v_files:
            file = os.path.join(p_folder_path, v_file)
            #with open(file, 'r') as files:
                #for lines in files.readlines():
                    #Tab.append([lines])
            with open(file, 'a') as file:
                file.write("\n add " + str(Random())) #Random = int
                #file.close

def Random():

    global last
    last = last + 3 + last * last * last * last % 256
    return last

def main ():

    Modif_Files(Modif_Path, 5) # Put path with a txt file inside
if __name__ == '__main__':
    main()

`

Kylar
  • 31
  • 1
  • 4

3 Answers3

1

After going through few other posts, it seems it is not possible to write in the middle of beginning of a file directly without overwriting. To write in the middle you need to copy or read everything after the position where you want to insert. Then after inserting append the content you read to the file. Source: How do I modify a text file in Python?

Community
  • 1
  • 1
XZ6H
  • 1,779
  • 19
  • 25
0

Okay, I found the solution ; with open(file, 'r+') as file:

r+ and it work like a charm :)

Kylar
  • 31
  • 1
  • 4
0

The given answer is incorrect and/or lacking significant detail. At the time of this question maybe it wasn't, but currently writing to specific positions within a file using Python IS possible. I came across this question and answer in my search for this exact issue - an update could be useful for others.

See below for a resolution.

def main():
    file = open("test.txt", "rb")
    filePos = 0
    
    while True:
        # Read the file character by character
        char = file.read(1)
        # When we find the char we want, break the loop and save the read/write head position.
        # Since we're in binary, we need to decode to get it to proper format for comparison (or encode the char)
        if char.decode('ascii') == "*":
            filePos = file.tell()
            break
        # If no more characters, we're at the end of the file. Break the loop and end the program.
        elif not char:
            break
       
    
    # Resolve open/unneeded file pointers.
    file.close()
    
    # Open the file in rb+ mode for writing without overwriting (appending).
    fileWrite = open("test.txt", 'rb+')
    
    # Move the read/write head to the location we found our char at. 
    fileWrite.seek(filePos - 1)
    
    # Overwrite our char.
    fileWrite.write(bytes("?", "ascii"))
    
    # Close the file
    fileWrite.close()
    
if __name__ == "__main__":
    main()
zNaCly
  • 33
  • 1
  • 5