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
  • 4

2 Answers2

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,760
  • 19
  • 25
0

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

r+ and it work like a charm :)

Kylar
  • 31
  • 4