1 回答

TA貢獻2065條經(jīng)驗 獲得超14個贊
我認為你想要做的是這樣的:
from ast import literal_eval
with open ("numbers.txt") as inFile:
lines = inFile.readlines()
for i, line in enumerate(lines,1): #start with 1 because excel row start with index = 1
line_number = literal_eval(line)
if 1800 in line_number :
cell1800_a = sheet.cell(row=i,column=27)
cell1800_a.value = number
cell1800_b = sheet.cell(row=i,column=29)
cell1800_b.value = number
if 2100 in line_number:
cell2100_a = sheet.cell(row=i,column=25)
cell2100_a.value = number
if 2600 in line_number :
cell2600 = sheet.cell(row=i,column=30)
cell2600.value = number
if 1500 in line_number :
cell1500 = sheet.cell(row=i,column=34)
cell1500.value = number
if 800 in line_number :
cell800 = sheet.cell(row=i,column=33)
cell800.value = number
if 3700 in line_number :
cell3700 = sheet.cell(row=i,column=40)
cell3700.value = number
我改變了什么:
我將輸入字符串評估為一個元組。原因是,例如,如果您在字符串中查找字符串 800,
(1800, 2100, 2600, 1500, 900, 3700)
您會找到匹配項,因為 1800 中有 800。因此,為了避免這種情況,我對其進行了評估,現(xiàn)在我正在研究一個正確數(shù)字的元組,因此只有當(dāng)數(shù)字 800 在元組中時它才會匹配,而在上面的示例中不是這種情況。您有 2 個 for 循環(huán),而第 2 個 for 循環(huán)是不必要的。我認為您希望 txt 文件的每一行都與您的 excel 文件中的行相對應(yīng)。但是使用您的第二個 for 循環(huán),您會覆蓋之前發(fā)生的每個匹配項,在最壞的情況下,您將擁有一個完整的 excel,并且僅針對最后一行評估相同的值?;旧?,您只需為每行寫入一次值,而不是多次。
else
部分是不必要的,pass
我刪除了它。
添加回答
舉報