Студент CS здесь, очень запутанный о том, как решить эту проблему ... mailingLabels.txt
- просто пустой текстовый файл.Запись в текстовый файл из списка
Вот один пример строки из customerData.txt
:
Eric,A,Stutler,568 Nuzum Court,East Aurora,NY,14052,US,[email protected],716-652-4943,male,11/24/1947
Инструкции:
Из функции main
называют новую функцию generateMailingLabels
обработать список клиентов для генерации текстовый файл, содержащий ярлыки для рассылки только для клиентов-клиентов в Айове (IA).
Общий подход вы должны принять это:
- передать
customerList
в качестве параметра этой функции - открыть файл наклейки (
mailingLabels.txt
) - функции должны перебираю все клиент записи в списке
- Если запись соответствует указанным выше критериям (женщина из Айовы), , создайте почтовую метку, объединив элементы выбора из запись клиента список полей, и
- написать этикетку рассылки в файл (
mailingLabels.txt
)
Каждая метка рассылки должен быть отформатирован, как показано ниже с 5 пустых строк разделения каждой метки:
Jane Smith 123 Main Street Cedar Falls, IA 50613
Это мой текущий код:
def main():
""" Opens file, reads customer information into a list, closes the file"""
custFile = open('customerData.txt','r')
customerList = generateList(custFile)
mailingList = open('mailingLabels.txt','w')
# Echo first and last enter from the customerList
print "customerList[0]:", customerList[0]
print "customerList[-1]:",customerList[-1]
custFile.close()
def generateList(custFile):
""" Reads customer data from file and returns a list of customers"""
customers = []
for line in custFile:
# Strip the new-line character from the end of the line, then split
# the line on the commas (',') to get a list of customer fields
custInfoList = line.strip().split(',')
customers.append(custInfoList)
return customers
def generateMailingLabels(customerList):
"""Sorts through the customer list and returns only females living in Iowa."""
mailingList
for customer in customerList:
if customer[5] == 'IA' and customer[10] == 'female':
mailingList.write(customer)
Я понимаю, что это, вероятно, легко сделать, мне просто трудно понять, как правильно закодировать его, чтобы он делал то, что я хочу, чтобы он делал. Любая помощь приветствуется.
EDIT: ОБНОВЛЕНО КОД:
def main():
""" Opens file, reads customer information into a list, closes the file"""
with (open('customerData.txt','r') as custFile,
open('mailingLabels.txt','w') as mailingList):
customerList = generateList(custFile)
generateMailingLabels(customerList, mailingList)
# Echo first and last enter from the customerList
print "customerList[0]:", customerList[0]
print "customerList[-1]:",customerList[-1]
def generateList(custFile):
""" Reads customer data from file and returns a list of customers"""
customers = []
for line in custFile:
# Strip the new-line character from the end of the line, then split
# the line on the commas (',') to get a list of customer fields
custInfoList = line.strip().split(',')
customers.append(custInfoList)
return customers
def generateMailingLabels(customerList,mailingList):
"""Sorts through the customer list and returns only females living in Iowa."""
open('mailingLabels.txt','w')
for customer in customerList:
if customer[5] == 'IA' and customer[10] == 'female':
mailingList.write(customer)
mailingList.close()
main()
Вероятно, вы должны вызвать 'generateMailingLabels' из' main'. И переместите оператор 'mailingList = open (...)' в 'generateMailingLabels'. – melpomene