![](/img/trans.png)
[英]how to split data from text file and create separate columns at a specific position by giving title for each column
[英]Replace specific column data with split and readlines in text file
文字檔:Hardware.txt
Model Year Plate Owner
Acer (2014) A12456 Nitik
Dell (2015) S45656 Dane
碼:
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) + "'.")
我有一個文本文件Hardware.txt,我想更新所有者的名稱,但是我總是會遇到此錯誤:
IndexError: list index out of range
請幫我更新文本文件
使用熊貓,您只需閱讀文件(確保分隔符是制表符而不是空格):
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")
如果您不想/不能使用熊貓,請先閱讀文件並構建新數據:
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
)分隔。 適應任何分隔它的地方(逗號,空格等)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.