我创建了一个文件,它将为文件创建数据,打印该文件,我现在正在尝试创建一个菜单程序,允许用户输入特定的颜色,然后该文件将打印出来该颜色的数据。我的代码如下:
def createFile(allColours):
colours = open("colours","w")
colours.write(str(allColours))
colours.close()
output()
def output():
colours = open("colours","r")
outputQuestion = input("Would you like the to see the output of the data for colours?(Y/N) \n")
if outputQuestion == "Y" or outputQuestion == "y":
for counter in range(4):
print(colours.readline())
colours.close()
menu()
def data():
allColours = []
allColours.append({"ID": "1", "Shade": "Black", "Red": "0", "Green": "0", "Blue":"0"})
allColours.append ({"ID": "2", "Shade": "White", "Red": "255", "Green": "255", "Blue":"255"})
allColours.append ({"ID": "3", "Shade": "Red", "Red": "255", "Green": "0", "Blue":"0"})
allColours.append ({"ID": "4", "Shade": "Green", "Red": "0", "Green": "255", "Blue":"0"})
allColours.append ({"ID": "5", "Shade": "Blue", "Red": "0", "Green": "0", "Blue":"255"})
createFile(allColours)
def menu():
colours = open("colours","r")
whatColour = input("What colour would you like to be looked up?\n")
if whatColour == "Black":
print(colours[0])
正如def菜单()显示的那样,我希望程序向用户询问要查找的颜色。例如,如果用户说黑色,程序应该打印该词典的详细信息。
我还想知道是否有一种方法使得在def output()中,每个数据条目将被新行分割。目前,当我打印它时,它出现如下的长列表:
[{'ID': '1', 'Shade': 'Black', 'Red': '0', 'Green': '0', 'Blue': '0'}, {'ID': '2', 'Shade': 'White', 'Red': '255', 'Green': '255', 'Blue': '255'}, {'ID': '3', 'Shade': 'Red', 'Red': '255', 'Green': '0', 'Blue': '0'}, {'ID': '4', 'Shade': 'Green', 'Red': '0', 'Green': '255', 'Blue': '0'}, {'ID': '5', 'Shade': 'Blue', 'Red': '0', 'Green': '0', 'Blue': '255'}]
答案 0 :(得分:1)
修改:未使用json
的尝试:
def createFile(allColours):
with open("colours","w") as colours_file:
for colour in allColours:
colours_file.write(str(colour))
colours_file.write('\n')
colours_file.close()
output()
def output():
outputQuestion = input("Would you like the to see the output of the data for colours?(Y/N) \n")
if outputQuestion.lower() == "y":
with open("colours","r") as colours_file:
for colour in colours_file.readlines():
print(colour, end='\r')
colours_file.close()
menu()
def data():
allColours = []
allColours.append ({"ID": "1", "Shade": "Black", "Red": "0", "Green": "0", "Blue":"0"})
allColours.append ({"ID": "2", "Shade": "White", "Red": "255", "Green": "255", "Blue":"255"})
allColours.append ({"ID": "3", "Shade": "Red", "Red": "255", "Green": "0", "Blue":"0"})
allColours.append ({"ID": "4", "Shade": "Green", "Red": "0", "Green": "255", "Blue":"0"})
allColours.append ({"ID": "5", "Shade": "Blue", "Red": "0", "Green": "0", "Blue":"255"})
createFile(allColours)
def menu():
colours_file = open("colours","r")
whatColour = input("What colour would you like to be looked up?\n")
for colour in colours_file.readlines():
if whatColour in colour.partition("\'Shade\': ")[2]:
print(colour)
data()
可能不熟悉或可能看似笨重的唯一部分是使用str.partition来查找与用户输入相匹配的颜色。