将特定列数据替换为文本fi中的拆分和读取行

2024-09-29 22:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

文本文件:Hardware.txt在

Model   Year    Plate   Owner
Acer    (2014)  A12456  Nitik
Dell    (2015)  S45656  Dane

代码:

^{pr2}$

我有一个文本文件硬件.txt我想更新所有者的名字,但我总是以这个错误告终:

IndexError: list index out of range

请帮我更新文本文件


Tags: 代码txtmodelyearhardwaredellowner文本文件
1条回答
网友
1楼 · 发布于 2024-09-29 22:19:48

使用pandas,只需读取文件(确保分隔符是制表符而不是空格):

df = pd.read_csv("Hardware.txt", sep = "\t")

Model   Year    Plate   Owner
0   Acer    (2014)  A12456  Nitik
1   Dell    (2015)  S45656  Dane

然后换个名字

^{pr2}$

并且保存

df.to_csv("Hardware.txt", sep="\t")

如果您不想/不能使用pandas,请首先读取文件并构建新数据:

id = 1 # just example; input your id
with open("Hardware.txt", "r") as f:
    content = f.readlines()
    lines = [x.strip().split("\t") for x in content]
    lines[id][-1] = "New Owner"

那就省省吧

with open("Hardware.txt", "w") as f:
    f.write("\n".join(["\t".join(x) for x in lines]))

请注意(再次)我假设您的文件由tabs\t)分隔。适应任何分隔它的地方(逗号、空格等)

相关问题 更多 >

    热门问题