[英]csv files and appending data to a list
我想知道是否有一種方法可以將數據追加到列表,但是只能將從csv文件讀取的數據的最后5個小數位添加到列表中。
下面是我將csv文件附加到列表的代碼示例。 目前,csv文件中的所有值(最多具有10個小數位)都已附加,但我只需要前5個位。 這可能嗎 ?
def main():
welcome_message()
user_input()
def welcome_message():
#will eventually display a welcome message and programme description
def user_input():
my_file = open('TestData.csv', 'rU')
calculation(my_file)
def calculation(my_file):
my_data = csv.reader(my_file)
next(my_data)
my_list = []
for row in my_data:
my_list.append(row) #append the csv data to a list
您可以使用format限制小數位數:
https://docs.python.org/2/library/string.html#format-specification-mini-language
def main():
welcome_message()
user_input()
def welcome_message():
#will eventually display a welcome message and programme description
def user_input():
my_file = open('TestData.csv', 'rU')
calculation(my_file)
def calculation(my_file):
my_data = csv.reader(my_file)
next(my_data)
my_list = []
for row in my_data:
x = '{:.5f}'.format(float(row))
my_list.append(x) #append the csv data to a list
請注意,我將字符串追加到列表中。 如果希望它們為浮點型,只需將它們轉換為float(x)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.