Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON: Any help would be appreciate. I\'ve tried readline command. Not getting

ID: 3769432 • Letter: P

Question

PYTHON:


Any help would be appreciate. I've tried readline command. Not getting much success.


The import.txt file attached to this Exam summarizes all of the company imports of petroleum products into the United States. Each line includes, as tab-separated values:

Write a Python program that asks for a product such as: Wax, Crude Oil, Propylene, NGL, Jet Fuel,…

It then reads the file line by line totaling that product’s total imports received at TEXAS ports.  To be correct it must handle multiple products until a return is entered without re-running your program. (ie, it uses a repetition or loop).

Test data:

What product do you want totaled? Feedstocks

1318 barrels of Feedstocks were imported into TEXAS.

What product do you want totaled? Crude Oil

88235 barrels of Crude Oil were imported into TEXAS.

What product do you want totaled? Wax

2 barrels of Wax were imported into TEXAS.

What product do you want totaled? Jet Fuel

0 barrels of Jet Fuel were imported into TEXAS.

What product do you want totaled? NGL

0 barrels of NGL were imported into TEXAS.

What product do you want totaled? Propylene

41 barrels of Propylene were imported into TEXAS.

What product do you want totaled??ß  A return here ends the program.

Explanation / Answer

You'll need open(name, mode), myfile.readlines(), mystring.split(), int(myval), and then you'll probably want to use a couple of generators to put them all together in a pythonic way.

# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]

=====================================

If the file to read is big, and you don't want to read the whole file in memory at once:

fp = open("file")
for i, line in enumerate(fp):
    if i == 25:
        # 26th line
    elif i == 29:
        # 30th line
    elif i > 29:
        break
fp.close()
============================================

def get_numbers_from_file(file_name):
    file = open(file_name, "r")
    strnumbers = file.read().split()
    return map(int, strnumbers)


print get_numbers_from_file("numbers.txt")