簡體   English   中英

通過字符串輸入查找行並替換 CSV 文件 Python 中的特定行

[英]Find line via string input and replace specific row in CSV file Python

對於地址簿項目,我需要通過 input() IE 在 CSV 文件中找到特定行,如果用戶輸入“Toast”,它將找到上面帶有 Toast 的行,然后替換該行上的一行,例如“Jam " 來自用戶的另一個輸入。

有沒有辦法做到這一點?

例子:

Bread,Condiment1,Condiment2
Toast,Butter,Jam, 

 #Finds Toast
    input = Toast
 #Replaces Jam with Nutella
    input = Nutella

然后應該變成

Bread,Condiment1,Condiment2
Toast,Butter,Nutella

我假設您總是想替換行的第三個元素。 所以我相應地寫了這個

with open('example.csv', 'r+', encoding='utf-8') as f:
    aa = f.readlines()
    x = input()
    for k,i in enumerate(aa):
        if i.startswith(x):
            y = input()
            words=i.split(',')
            words[2] = y
            aa[k] =','.join(words)
    f.seek(0)
    f.write(''.join(aa))
    f.truncate()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM