2016-05-21 39 views
0

我的銷售記錄需要幫助。我的程序會調用我的文本文件中的信息。下面 此代碼:記錄過程。 - 在.txt文件中調用信息。 Python

text_file = open("data.txt", "r") 

lines = text_file.readlines() 

print (lines) 

print (lines) 

text_file.close() 

打開包含以下信息我的data.txt文件:

1-2-2014,Frankton,42305.67,23 
12-4-2014,Glenview,21922.22,17 
10-2-2015,Glenview,63277.9,32 
10-5-2015,Glenview,83290.09,16 
11-6-2015,Frankton,81301.82,34 
10-10-2015,Frankton,62333.3,40 
11-11-2015,Frankton,28998.8,29 
1-1-2016,Glenview,51083.5,27 
1-3-2016,Glenview,62155.72,42 
27-3-2016,Frankton,33075.1,18 
2-4-2016,Glenview,61824.7,35 

我怎樣寫一個無返回值的函數print_all_records(記錄)。如果該函數將列表作爲周長並顯示記錄,則每行記錄一條記錄。在不同的標題下。

示例引用data.txt文件。它應該在打印時顯示。每行包含文本文件中的信息。

Date   Branch    Daily Sale   Transactions 
01/02/2014 Frankton   $42305.67   23 
12/04/2014 Glenview   $219.22.22   17 
+0

退房https://pypi.python.org/pypi/PrettyTable。這不完全是你想要的格式,但它很容易使用,也很好看。 –

+0

這是作業還是作業? –

回答

0

如果您存儲的每一行作爲一個列表的字符串,你可以使用:

def print_all_records(records): 
    print("Date" + "\t\t" + "Branch" + "\t\t" + "Daily Sale" + "\t\t" + "Transactions") 
    for record in records: 
     parts = record.split(",") 
     print(parts[0] + "\t" + parts[1] + "\t" + "$" + parts[2] + "\t\t" + parts[3]) 

可以標籤(\t)的數量明顯調整,以自己的喜好。

0

您可以使用熊貓 -

import pandas as pd 

df = pd.read_csv('file_name.txt', header = None) 

df.columns = ['Date', 'Branch', 'Daily Sale', 'Transactions'] 

print(df.to_string(index = False, justify = 'left')) 

輸出 -

Date  Branch  Daily Sale Transactions 
    1-2-2014 Frankton 42305.67 23   
    12-4-2014 Glenview 21922.22 17   
    10-2-2015 Glenview 63277.90 32   
    10-5-2015 Glenview 83290.09 16   
    11-6-2015 Frankton 81301.82 34   
10-10-2015 Frankton 62333.30 40   
11-11-2015 Frankton 28998.80 29   
    1-1-2016 Glenview 51083.50 27   
    1-3-2016 Glenview 62155.72 42   
    27-3-2016 Frankton 33075.10 18   
    2-4-2016 Glenview 61824.70 35 
+0

謝謝。 importerror:沒有名爲pandas的模塊 –

+0

Pandas是一個外部模塊。你必須安裝它。 –

+0

哦謝謝你。我也想知道我的程序是否有通過data.txt文件搜索的方法?例如,如果您輸入的日期與data.txt文件中的日期相匹配,則會打印出其信息。 (我可能需要開始一個新的線程wouldnt我?) –