簡體   English   中英

如何使用 python 腳本刪除文件每行中“==”后的所有字符並更新文件?

[英]How to delete all characters after a “==” in each line of a file and update the file, using python script?

我有一個龐大的 python 軟件包列表,這些軟件包已安裝並保存在文件“foo.txt”中的版本號,我想刪除每行中的“==”以及之后的任何內容,然后保存文件。

文件中的示例文本:

autopep8==1.5.3
beautifulsoup4==4.8.2
bleach==3.1.4
bumpversion==0.5.3
... etc

使用下面的代碼。

讀取該文件並將其存儲在名為 pkg_list 的列表中。

output_lst = []
with open("input.txt", "r") as f:
    input_data = f.readlines()
    output_lst = [name.split("==")[0] for name in input_data]

with open("input.txt", "w") as f:
    for pkg in output_lst:
        f.write("{}\n".format(pkg))

如果您想創建一個包含更新數據的新文件,請使用這行代碼,如果您只想讀取數據,請相應地進行更改。

def read_write_file(input_path, output_path):
    with open(input_path, "r") as input_file:
        content = input_file.readlines()

    with open(output_path, 'w') as output_file:
        for line in content:
            line = line[:line.find('==')]
            output_file.write(line + '\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM