我是一位网络工程师,试图使用Python学习编程。我对任何形式的编程都是新手。
我正在尝试从.csv文件中搜索列1中的值,并返回对应列的字符串。执行程序时,它将遍历所有单元格,显示每个单元格的结果。我想要的是,如果用户输入数字,则需要搜索列表,一旦找到匹配项,则返回下一列的字符串。如果用户输入的值不存在,则返回打印语句。
import csv
import sys
fileName = 'sip.csv'
READ = 'r'
WRITE = 'w'
enter_code = input('Enter The Sip Response Code: ')
with open(fileName, READ) as myXLfile:
dataFromFile = csv.reader(myXLfile)
for currentRow in dataFromFile:
if enter_code == currentRow[0]:
print("The SIP Response Code you entered is: " + enter_code)
print("The SIP Message is: " + currentRow[1])
print("Meaning: " + currentRow[2])
break
if enter_code != currentRow[0]:
print("Im Sorry, I Do not have this Response Code")
else:
print("Thank You and Goodbye")
结果:
Enter The Sip Response Code: 200
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
The SIP Response Code you entered is: 200
The SIP Message is: OK
Meaning: The request has been successfully processed and the result of the request is transmitted in the response.
答案 0 :(得分:1)
您的意思是这样的:
import csv
fileName = 'sip.csv'
READ = 'r'
WRITE = 'w'
check = True
enter_code = input('Enter The Sip Response Code: ')
with open(fileName, READ) as myXLfile:
dataFromFile = csv.reader(myXLfile, delimiter=";")
for currentRow in dataFromFile:
if enter_code == currentRow[0]:
print("The SIP Response Code you entered is: " + enter_code)
print("The SIP Message is: " + currentRow[1])
print("Meaning: " + currentRow[2])
check = False
break
if check:
print("Im Sorry, I Do not have this Response Code")
else:
print("Thank You and Goodbye")
答案 1 :(得分:0)
类似的东西应该对您有用。
# Select All From CSV File Where
import csv
# Asks for search criteria from user
search_parts = input("Enter search criteria:\n").split(",")
# Opens csv data file
file = csv.reader(open("C:\\your_path\\test.csv"))
# Go over each row and print it if it contains user input.
for row in file:
if all([x in row for x in search_parts]):
print(row)