【问题标题】:How to modify last line of a file using python in linux如何在linux中使用python修改文件的最后一行
【发布时间】:2020-08-04 07:35:34
【问题描述】:

我有一个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 注释/取消注释文件的最后一行。谢谢

【问题讨论】:

    标签: python-3.x file


    【解决方案1】:

    你不能像预期的那样简单。一种解决方案是将# 添加到相关行并重写整个文件。

    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) 将行列表变回字符串。

    【讨论】:

    • 感谢这个好建议。如果我想从最后一行删除#,我该怎么办
    • 代替contents[-1] = '#' + contents[-1],添加contents[-1] = contents[1:]
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2010-10-14
    • 2011-07-02
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    相关资源
    最近更新 更多