gpt4 book ai didi

python - 使用 Python 替换文本文件中以逗号分隔的特定列中的单词

转载 作者:太空宇宙 更新时间:2023-11-03 18:21:13 25 4
gpt4 key购买 nike

抱歉,我只是在说 Python 并且需要一些提示

我有一个如下所示的列表:

$ cat server.txt
column1, column2, column3, column4, column5
server1, windows, 120, running , 1
server2, linux, 250, offline , 1
server3, centos, 60, maintenance, 0
server4, windows, 123, running, 1
server5, linux, 145, offline, 0

我需要将第二列替换为其他值,例如:

第 5 列中的所有 1 均替换为单词 noissue,0 替换为单词 issue但只有第 5 列,因为我不想让第 3 列受到更改的影响

非常感谢

最佳答案

如果您确定要替换的列仅包含 0 和 1,则此操作将起作用。

firstline = True
with open("server.txt") as f:
with open("output.txt", "w") as fw:
for line in f.readlines(): # For each line in server.txt

if firstline: # Do not process the header line
firstline = False
continue

if line[-2] == "1": # -2 because -1 is the line return character
line = line[:-2] + "noissue\n"
else:
line = line[:-2] + "issue\n"
fw.write(line)

关于python - 使用 Python 替换文本文件中以逗号分隔的特定列中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24105871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com