Чтобы добавить строку в конец файла в Python, вы можете использовать несколько методов. Вот несколько вариантов:
-
Метод 1: использование функции
open()
с режимом «a» (добавление):with open("filename.txt", "a") as file: file.write("This is the line to be added at the end of the file.")
-
Способ 2: открытие файла в режиме записи с помощью опции «a» (добавление):
file = open("filename.txt", "a") file.write("This is the line to be added at the end of the file.") file.close()
-
Метод 3: использование оператора
with open()
в режиме «a» (добавление):line_to_add = "This is the line to be added at the end of the file." with open("filename.txt", "a") as file: file.write(line_to_add)
-
Метод 4: использование функций
seek()
иwrite()
:with open("filename.txt", "r+") as file: file.seek(0, 2) # Move the cursor to the end of the file file.write("This is the line to be added at the end of the file.")