簡體   English   中英

Python將文本文件中每行的最后一個數字放入列表中

[英]Python take the last number of each line in a text file and make it into a list

我只想要每行的最后一個號碼。

with open(home + "/Documents/stocks/" + filePath , newline='') as f:
stockArray = (line.split(',') for line in f.readlines())
    for line in stockArray:
        List = line.pop()
        #print(line.pop())
        #print(', '.join(line))
else:
    print("Finished")

我嘗試使用line.pop()獲取最后一個元素,但僅從一行開始獲取它? 如何從每一行中獲取它並將其存儲在列表中?

您可能只想要以下內容:

last_col = [line.split(',')[-1] for line in f]

對於更復雜的csv文件,您可能需要查看標准庫中的csv模塊,因為它將正確處理字段引用等。

my_list = []
with open(home + "/Documents/stocks/" + filePath , newline='') as f:
    for line in f:
        my_list.append(line[-1]) # adds the last character to the list

那應該做。

如果要添加文件中列表的最后一個元素:

my_list = []
with open(home + "/Documents/stocks/" + filePath , newline='') as f:
    for line in f:
        my_list.append(line.split(',')[-1]) # adds the last character to the list

暫無
暫無

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

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