Reputation: 69
I want to read lines from a file and print the contents in a list of tuples.
But I'm getting two commas during conversion.
I'm having trouble find out the way to remove the comma that is more.
Code:
def arrivalsFile(file_name):
"""
Reads part of an input file with the arrivals into a list of flights.
Requires: file_name, for arrivals, is a text file with the structure indicated in the quizz
Ensures: list of tuples, each corresponding to one flight
>>> arrivalsFile("arrivals_14_16.txt")
[('KLM75', 'Amsterdam', '14:35', '60', '50'), ('AF111', 'Paris', '14:20', '50', '64'), ('LH333', 'Frankfurt', '14:10', '112', '203'), ('KLM71', 'Madrid', '14:55', '120', '100'), ('TAP103', 'Salvador', '15:20', '174', '210'), ('LH123', 'Berlin', '15:10', '115', '210')]
"""
lista = []
inFile = open(file_name, "r")
for line in inFile:
if "Arrivals:" in line:
for line in inFile:
lista.append(tuple(line.split()))
inFile.close()
Execution:
**********************************************************************
File "Z:\Documents\1415\airConveyorBeltsGroup11\readInput.py", line 9, in __main__.arrivalsFile
Failed example:
arrivalsFile("arrivals_14_16.txt")
Expected:
[('KLM75', 'Amsterdam', '14:35', '60', '50'), ('AF111', 'Paris', '14:20', '50', '64'), ('LH333', 'Frankfurt', '14:10', '112', '203'), ('KLM71', 'Madrid', '14:55', '120', '100'), ('TAP103', 'Salvador', '15:20', '174', '210'), ('LH123', 'Berlin', '15:10', '115', '210')]
Got:
[('KLM75,', 'Amsterdam,', '14:35,', '60,', '50'), ('AF111,', 'Paris,', '14:20,', '50,', '64'), ('LH333,', 'Frankfurt,', '14:10,', '112,', '203'), ('KLM71,', 'Madrid,', '14:55,', '120,', '100'), ('TAP103,', 'Salvador,', '15:20,', '174,', '210'), ('LH123,', 'Berlin,', '15:10,', '115,', '210')]
**********************************************************************
1 items had failures:
1 of 1 in __main__.arrivalsFile
***Test Failed*** 1 failures.
Upvotes: 1
Views: 194
Reputation: 13222
You need to split at the ,
.
>>> line = 'KLM75, Amsterdam, 14:35, 60, 50'
>>> print(tuple(line.split(',')))
('KLM75', ' Amsterdam', ' 14:35', ' 60', ' 50')
If you need to get rid of leading and trailing spaces use the following.
>>> print(tuple(element.strip() for element in line.split(',')))
('KLM75', 'Amsterdam', '14:35', '60', '50')
According to your comment you don't want to use a list comprehension. Well, technically I used a generator expression, not a list comprehension, but I modified your code to show what you want.
lista = []
inFile = open(file_name, "r")
for line in inFile:
if "Arrivals:" in line:
data = []
for line in inFile:
for element in line.split(','):
data.append(element.strip())
lista.append(tuple(data))
inFile.close()
For each line we create a new list called data
, append the stripped elements to this list and transform this list to a tuple after we looped over all elements in the line.
Upvotes: 0