Как изменить последнюю строку файла, используя python в linux - PullRequest
0 голосов
/ 04 августа 2020

У меня есть file.txt с содержанием ниже:

A "Hello, World!" program generally is a computer program that outputs or displays the message "Hello, World!". 
Such a program is very simple in most programming languages, and is often used to illustrate the basic syntax of a programming language. 
It is often the first program written by people learning to code.[1][2] It can also be used as a sanity test to make sure that a computer 
language is correctly installed, and that the operator understands how to use it

Hello world

В самой последней строке файла у меня есть предложение Hello world, которое я хочу прокомментировать #, чтобы он становится #Hello world. Как я могу прокомментировать / раскомментировать последнюю строку файла, используя python3. Спасибо

1 Ответ

1 голос
/ 04 августа 2020

Вы не можете сделать это так просто, как ожидалось. Одно из решений - добавить # к соответствующей строке и переписать весь файл.

file.txt:

A "Hello, World!" program generally is a computer program that outputs or displays the message "Hello, World!". 
Such a program is very simple in most programming languages, and is often used to illustrate the basic syntax of a programming language. 
It is often the first program written by people learning to code.[1][2] It can also be used as a sanity test to make sure that a computer 
language is correctly installed, and that the operator understands how to use it

Hello world

main.py:

fname = "file.txt"

with open(fname, "r") as f:
  contents = f.readlines()

# Last line is at -1.
contents[-1] = '#' + contents[-1]

with open(fname, "w") as f:
  f.write("".join(contents))

"".join(contents) превращает список строк обратно в строку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...