如何仅显示包含输入值的csv文件中的行,使用python进行对齐3.6.1
问题描述:
我似乎无法在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
答
你能用下面的代码吗?
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
答
您的格式问题简单解决的。
你的编码格式的标题是这样的:
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
应该是文件中的值(如果是这样,哪一个?距离,也许?),或者是什么?换句话说,你希望选择发生在什么基础上?如果你想得到答案,那需要解决你的问题。
您如何期待它的工作?你甚至不会把'Num'传递给'info'。 –