2017-08-05 67 views
0

我似乎無法在csv文件中找到輸入值,只顯示包含輸入值的行。 csv數據與打印標題的對齊也是我正在努力解決的一個問題。如何僅顯示包含輸入值的csv文件中的行,使用python進行對齊3.6.1

import csv 

def menu(): 
     print("Menu") #Prints menu page to select option 
     print("======") 
     print("[1]: Display info") 
     print("[0]: Exit") 

def info(): 
    read = csv.reader(open("value.csv", "r")) 
    for j in read: 
     print(j[:4]) 

while True: 
    menu() 
    selection = int(input("Enter your selection: ")) #Choose selection from menu 

    if selection == 1: 
     print("1: Display info") 
     print() 
     Num = str(input("Enter a value.: ")) #Input value to find for match, refers to the Value in value.csv file 
     print("{:<10}{:<15}{:<15}{:<11}".format("Value", "Time", "Distance", "Pace")) #Prints heading 
     print("{:<10}{:<15}{:<15}{:<11}".format("--------", "-------------", "-------------", "---------")) #Prints heading with alignment 
     info() #Executes def function 

    elif selection == 0: 
     break #Exit from program 
+4

您如何期待它的工作?你甚至不會把'Num'傳遞給'info'。 –

回答

0

你能用下面的代碼嗎?

finder.py

import csv 
from collections import OrderedDict 

tofind = input("String to find:") 

print("{:<10}{:<10}".format("Index", "Value")) 

with open('data.csv', 'r') as csvfile: 
    content = csv.reader(csvfile, delimiter=',') 
    for index, value in content: 
     if (value == tofind): 
      print("{:<10}{:<10}".format(index, value)) 

data.csv

1,test 
2,ok 
3,findme 
4,test 
5,random 
6,findme 
7,findme 
8,no 
9,yes 
10,findme 

輸出

➜ python python3 finder.py 
String to find:yes 
Index  Value  
9   yes  
➜ python python3 finder.py 
String to find:findme 
Index  Value  
3   findme  
6   findme  
7   findme  
10  findme  

HTH

0

您的格式問題簡單解決的。

你的編碼格式的標題是這樣的:

print("{:<10}{:<15}{:<15}{:<11}".format("Value", "Time", "Distance", "Pace")) 

但打印數據做任何排版功能:

print(j[:4]) 

如果您希望將數據與標題排隊你需要這樣格式化:

print("{:<10}{:<15}{:<15}{:<11}".format(*j[:4])) 

雖然通常有數字,並且c右上角不是左對齊(>而不是<),我個人偏好是居中日期和時間(^而不是<)。

COLDSPEED已經回答了您的其他問題。功能info()列出.csv文件中的所有內容。如果要過濾Num的值,則需要將Num傳遞給info()函數,並在該函數中執行if-測試,以選擇用戶想要查看的數據。

我們不能說出if-測試應該是什麼。 Num應該是文件中的值(如果是這樣,哪一個?距離,也許?),或者是什麼?換句話說,你希望選擇發生在什麼基礎上?如果你想得到答案,那需要解決你的問題。

相關問題