简体   繁体   中英

Replace specific column data with split and readlines in text file

Text file:Hardware.txt

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

Code:

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) + "'.")

I have a text file Hardware.txt and I want to update the name of the owner but I always end up this error:

IndexError: list index out of range

Please help me to update the text file

With pandas, you just read your file (make sure the separators are tabs instead of spaces):

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

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

Then change the name

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

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

And save

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

If you do not want to/cannot use pandas, first read your file and build your new data:

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"

Then just save

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

Just notice (again) that I assumed your file is separated by tabs ( \\t ). Adapt for whatever separates it (comma, spaces, etc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM