Я хочу знать правильный алгоритм/способ поиска и изменения определенного элемента моего 2D-списка. Измененный 2D-список будет позже записан в CSV-файл. Ниже мой скрипт:
import csv
search = input("Enter name to find: ")
replace = input("Enter name replacement: ")
pendingFile = csv.reader(open("pendingLists.csv", "r"), delimiter = ",")
#Problem 1 -> Searching and Modifying algorithm here...
#Problem 2 -> Writing Algorithm here where the row is modified...
>>>Enter name to find: Mark
>>>Enter name replacement: Jave
Old listfile
~listFile.csv
Job,PB01
Mark,NU01
Jumeirah,SC01
Same modified listfile
~listFile.csv
Job,PB01
Jave,NU01
Jumeirah,SC01
Предлагаемый алгоритм поиска, который я нашел в Интернете, но до сих пор не модифицировал его для синтеза в моем коде.
for row in pendingFile:
if search == row[0]:
print(row)
Я еще новичок и уже 2 дня серфю в гугле и ютубе но не хватает прорывов с этой проблемой. Мне действительно нужна помощь, я студент, и нам поручено создать GUI POS Python 3 Tkinter в качестве финального индивидуального проекта.
Моя текущая проблема с программированием может быть большой для меня, но я искренне благодарен за щедрую помощь, которую вы можете предложить.






Трехстрочный фрагмент, который вы разместили, правильный.
Возможно, вам будет удобнее использовать программу чтения словарей: https://docs.python.org/3/library/csv.html#csv.DictReader.
Затем, прочитав файл, вы получите список dict в памяти, и вместо загадочного 0 вы можете использовать символическое имя столбца для каждого доступа, как показано ниже.
for row in rows:
if search == row['name']:
print(f'Found {search}, converting to capitals.')
row['name'] = search.upper()
Сделав несколько таких изменений, вы, вероятно, захотите сохранить обновленные строки с помощью DictWriter.
def dataRead():
with open("Inventory_List.csv", "r") as my_csv:
myFile = csv.reader(my_csv, delimiter = ",")
global dataInventoryList
dataInventoryList = [[col[0], col[1], col[2], col[3], col[4], eval(col[5])] for col in myFile]
def dataWrite():
with open("Inventory_List.csv", "w+") as my_csv:
myFile = csv.writer(my_csv, delimiter=',', lineterminator='\n')
myFile.writerows(dataInventoryList)
def main():
while True:
found = False
dataRead()
print("========================================================================= = ")
print("Before update;")
for i in range(len(dataInventoryList)):
for j in range(6):
print(str(dataInventoryList[i][j]) + "\t", end = "")
print("")
search = input("Enter product code: ")
quantity = int(input("Please enter quantity: "))
choice = int(input("Add stocks[1] Pull Stacks[2]\nChoice: "))
for i in range(len(dataInventoryList)):
if search == dataInventoryList[i][0]:
found = True
if choice == 1:
dataInventoryList[i][5] += quantity
break
elif choice == 2:
if dataInventoryList[i][5] == 0:
print("Requested order is out of stocks!\n")
break
elif quantity > dataInventoryList[i][5]:
print("Requested order is out of range!\n")
break
elif quantity <= dataInventoryList[i][5]:
dataInventoryList[i][5] -= quantity
break
if found == False:
print("Requested order was not found on the database!\n")
elif found == True:
dataWrite()
print("After update;")
for i in range(len(dataInventoryList)):
for j in range(6):
print(str(dataInventoryList[i][j]) + "\t", end = "")
print("")
main()
Решено! для столбца в my_csv: dataInventoryList.append([col[0], col[1]])