【发布时间】:2021-06-24 00:16:46
【问题描述】:
我正在阅读一个文件,其中只有第 1 列和第 3 列是我感兴趣的。在收集第一列的时间戳和第三列的产品名称并将数据存储在列表中之后,我打算打印一条消息:“产品 Y 的时间戳 X”。以下是我现在拥有的:
def reading_file():
file_reading = open("marjoja.txt", "r", encoding="utf-8")
# removing the header
file_reading.readline()
products = []
while (True):
row = file_reading.readline()
if len(row) == 0:
break
else:
# collecting data from 1 and 3 columns
lines = row.split(';')[0::2]
#products.append(row.split(';')[0::2])
products.extend(lines)
file_reading.close()
return products
def main():
products = reading_file()
product_lst = str(products).split("\n")
for lines in product_lst:
if lines == "0":
break
else:
print("Time", lines.split()[1], "on product", lines.split()[0],".")
main()
print(products) 的输出将是:['jordans', '00:00\n', 'polish', '02:13\n']。我想主要制作的是-“乔丹的时间00:00”。我正在生成的是:“['jordans', 的时间'00:00\n'。我如何将列表中的单词分配到正确的位置?
【问题讨论】:
-
您正在处理文件的每隔一行。将
removing the header部分移到循环之前。