1

I am trying to append some text to the beginning of a file in python, however rather than appending text to the file, it creates a new file with the same name, and writes to that file.

#!/usr/bin/env python3
import os
files = 'f0_ascii'
x = 0
for file in os.listdir(files):
    x += 1
    with open(file, 'a') as file2:
        y = 0
        for line in file:
            y += 1
        file2.seek(0, 0)
        string_in_string = "sometext {}".format(y - 10)
        file2.write(string_in_string)
        file2.close()
        if x == 1:
            exit()

I want it to append the beginning of the existing file with "sometext {}".format(y-10)

  • Related: [Prepend line to beginning of a file](https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file) – pault Apr 04 '19 at 14:28
  • 1
    Can I ask why do you open your file in a loop? What does your script do? – Heavenly Raven Apr 04 '19 at 14:36
  • I want to do the same thing to all the files in the folder 'f0_ascii', so the intention is that it opens the first file, appends it, then the second and so on –  Apr 04 '19 at 14:41
  • 2
    When you open a file in `append` mode, it tries to *append* the data, which means add it at the end. But then your code does a `seek()` to the beginning of the file. After that what you write to that file will overwrite what was there before. There isn't a `prepend` mode. You can't easily do what you want with a textfile because they are not really designed for random access. – BoarGules Apr 04 '19 at 14:49
  • Next question. Why do you need that x? You just exit after first iteration. – Heavenly Raven Apr 04 '19 at 14:51
  • Because the code doesn't currently work so there's no point doing it for more than one file –  Apr 04 '19 at 14:51
  • @BoarGules ah that's where I was going wrong, I changed it so that it reads the file, and saves the content, then creates a new file which prints the new information, then the contents of the original –  Apr 04 '19 at 14:53

1 Answers1

0

It works if the folder directory is specified:

import os
files = 'my_folder'


def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)


for file in os.listdir(files):

    y = 0
    for line in file:
        y += 1
    line_prepender(r'my_folder\{}'.format(file), "sometext {}".format(y - 10))

If it's not specified, open() just can't find your files in the current directory, so it just creates and opens them there.

EDIT: Used some code from here to make this script do exactly what you want.

  • I think the problem actually has to do with how appending to a file automatically occurs at the end, as boargules said in the comments. And I solved this problem by running the code from the directory –  Apr 04 '19 at 15:16