使用文本文件中的split和readlines替换特定列数据

时间:2018-04-21 13:44:15

标签: python python-3.x file

文本文件:Hardware.txt

5f854fc73292

代码:

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

我有一个文本文件Hardware.txt,我想更新所有者的名字,但我总是最终出现此错误:

enterId =int(input("Enter record ID: "))
openingFile = open('Hardware.txt', 'r')
    for data in openingFile:
        abc = data.split()
        lines = openingFile.readlines()
        if lines[enterId] in lines:
            nameOwner = input("Enter new owner name: ")
            b = lines[enterId].replace(abc[3], nameOwner)
            f = open('Hardware.txt', 'w')
            f.write(b)
            f.close()
            print(lines[enterId] + ' has been updated.')
        else:
            print("There is no records with ID '" + str(enterId) + "'.")

请帮我更新文本文件

1 个答案:

答案 0 :(得分:1)

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

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

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

然后更改名称

df.loc[df.Owner == "Dane", "Owner"] = "New Owner"

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

并保存

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)分隔。适应任何分隔它(逗号,空格等)