-1
def append_csv_file(filename):
    with open (filename, "a") as csv_file:
        file_name = csv_file
        appending = input("please enter the number of times you would like to enter "
                          "some text into the file on a different line: ")
        appending = int(appending)
        for appending in range(appending):
            x = input("please enter what you would like to append: ")
            file_name.write("\n" + x)

        exit()


xxx = input("please enter the file you would like to append to the file: ")
print(append_csv_file(xxx))

how do i make this code append into a certain line

Sayse
  • 42,633
  • 14
  • 77
  • 146
Casey Howard
  • 21
  • 1
  • 4
  • 2
    See [Is it possible to modify lines in a file in-place?](https://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place) – Peter Wood Aug 28 '18 at 12:12

1 Answers1

0

If you'd like to insert a new line into an existing file, you actually have to rebuild the file (atleast from that point on). This is because programmatically speaking, all the lines below it are different.

What I would do is read the entire file into a list, then merge the line you want to create into said list, and then write the output to a new file.

Alex
  • 144
  • 16
  • You actually can modify a file in-place with Python – gogaz Aug 28 '18 at 12:22
  • You can change the line, but if you want to insert it you would need to change all the following lines as well (to show the one below it) – Alex Aug 28 '18 at 12:23