예제 #1
0
파일: 2B.py 프로젝트: etscrivner/dse
def write_file(file_path):
    """Requests a series of numerical inputs and writes them to the file.

    Arguments:
        file_path(basestring): The path to the file
    """
    if os.path.isfile(file_path):
        should_overwrite = io.yes_no_prompt('File {} exists. Overwrite?')
        # If the file shouldn't be overwritten, abort
        if not should_overwrite:
            return

    total_num_entries = io.get_and_confirm_input(
        'How many numbers will you enter: ')
    total_num_entries = int(total_num_entries)

    num_entries_given = 0

    with open(file_path, 'w') as wfile:
        while num_entries_given < total_num_entries:
            value = io.get_and_confirm_input(
                'Entry #{}: '.format(num_entries_given + 1))
            value = float(value)
            wfile.write('{}\n'.format(value))
            num_entries_given += 1
예제 #2
0
파일: 8B.py 프로젝트: etscrivner/dse
    def execute(self, maximum_list_length):
        """Prompt user for a file and have them enter values to write into it.

        Arguments:
            maximum_list_length(int): The maximum allowed list length.
        """
        output_file = io.prompt_valid_file_name(
            'Please enter the file to write: ')

        if os.path.isfile(output_file):
            self.prompt_overwrite_or_change(output_file, maximum_list_length)

        if not os.path.exists(os.path.dirname(output_file)):
            self.directory_does_not_exist(output_file, maximum_list_length)

        total_num_entries = int(io.get_and_confirm_input(
            'How many numbers will you enter: '))
        num_entries_given = 0
        entries = []

        while num_entries_given < total_num_entries:
            value = io.get_and_confirm_list(
                'Entry {}: '.format(num_entries_given + 1),
                max_list_length=maximum_list_length)
            entries.append(value)
            num_entries_given += 1

        io.write_lists_to_file(output_file, entries)
        print 'Results written to {}'.format(output_file)
예제 #3
0
파일: 1A.py 프로젝트: etscrivner/dse
def main():
    """The application entry point"""
    print 'EXERCISE 1A'
    print '==========='
    print 'This program takes a CSV file, asks you to select a row from that'
    print 'file, and then computes the mean and standard deviation of the'
    print 'values in that row.'
    print
    file_path = io.get_and_confirm_input('Enter csv file with values: ')
    data = io.read_csv_file(file_path)

    if not data:
        raise RuntimeError('No data found in file {}'.format(file_path))

    column = io.choose_from_list(
        'Which column would you like to use:', data[0].keys())

    if column not in data[0]:
        raise RuntimeError('Invalid column {}'.format(column))

    values = linked_list.LinkedList()
    for each in data:
        values.insert(each[column])

    for each in values:
        print each

    print 'Mean: ', statistics.mean(values)
    print 'Std Dev: ', statistics.standard_deviation(values)
예제 #4
0
파일: 1B.py 프로젝트: etscrivner/dse
def main():
    """Application entry point"""
    print "Exercise 1B"
    print "==========="
    print "This program allows you to write or read a file containing floating"
    print "point values."
    print
    read_write = io.binary_choice("Mode ((r)ead/(w)rite): ", "r", "w")
    file_path = io.get_and_confirm_input("Please enter a file name: ")
    if read_write == "r":
        read_file(file_path)
    else:
        write_file(file_path)
예제 #5
0
파일: 3B.py 프로젝트: etscrivner/dse
def prompt_for_output_file(original_file_name):
    """Prompt for the file to output data into

    Arguments:
        original_file_name(str): The original file name.

    Returns:
        str: The new file name if a new file is entered, otherwise the original
             file name.
    """
    print "Origin file: {}".format(original_file_name)
    choice = io.binary_choice("Output file (s)ame/(n)ew file? ", "s", "n")
    if choice == "n":
        new_file_name = io.get_and_confirm_input("New file name: ")
        return new_file_name
    return original_file_name
예제 #6
0
파일: 2B.py 프로젝트: etscrivner/dse
def prompt_for_output_file(original_file_name):
    """Prompt for the file to output data into

    Arguments:
        original_file_name(str): The original file name.

    Returns:
        str: The new file name if a new file is entered, otherwise the original
             file name.
    """
    print 'Origin file: {}'.format(original_file_name)
    choice = io.binary_choice('Output file (s)ame/(n)ew file? ', 's', 'n')
    if choice == 'n':
        new_file_name = io.get_and_confirm_input('New file name: ')
        return new_file_name
    return original_file_name
예제 #7
0
파일: 2B.py 프로젝트: etscrivner/dse
def modify_file(file_path):
    """Modifies the values in the given file.

    Arguments:
        file_path(str): A file to be modified
    """
    numbers = io.read_numbers_from_file(file_path)
    output_file = prompt_for_output_file(file_path)

    # Go through each number one at a time
    results = []

    for idx, each in enumerate(numbers):
        # Display the results up to this point
        if results:
            print 'Numbers So Far:'
            for num in results:
                print num
        # Otherwise display next number
        print 'Next Number:'
        print each
        # Let the user choose what to do with the number
        choice = io.choose_from_list(
            'What would you like to do',
            ['Keep', 'Modify', 'Delete', 'Keep Rest']
        )
        choice = choice.lower()
        if choice == 'keep':
            results.append(each)
        elif choice == 'modify':
            number = io.get_and_confirm_input("New value: ")
            results.append(float(number))
        elif choice == 'keep rest':
            results += numbers[idx:]
            break
        elif choice == 'delete':
            # Do nothing
            pass

    # Write the updated numbers to the output file
    io.write_numbers_to_file(output_file, results)
    print 'Results written to ', output_file
예제 #8
0
파일: 3B.py 프로젝트: etscrivner/dse
def main():
    """Application entry point"""
    print "This program will read or write numbers to or from a given file."
    file_path = io.get_and_confirm_input("Please enter a file name: ")
    print "Read - Read and display numbers in a file"
    print "Write - Input numbers to write to a file"
    print "Add - Go through file line-by-line and add new numbers"
    print "Modify - Go through file line by line and modify numbers"
    mode = io.choose_from_list("Choose a mode", ["Read", "Write", "Add", "Modify"])
    mode = mode.lower()
    if mode == "read":
        read_file(file_path)
    elif mode == "write":
        write_file(file_path)
    elif mode == "add":
        add_file(file_path)
    elif mode == "modify":
        modify_file(file_path)
    else:
        raise RuntimeError("Invalid option {}".format(mode))
예제 #9
0
파일: 2B.py 프로젝트: etscrivner/dse
def main():
    """Application entry point"""
    print "This program will read or write numbers to or from a given file."
    file_path = io.get_and_confirm_input('Please enter a file name: ')
    print 'Read - Read and display numbers in a file'
    print 'Write - Input numbers to write to a file'
    print 'Add - Go through file line-by-line and add new numbers'
    print 'Modify - Go through file line by line and modify numbers'
    mode = io.choose_from_list('Choose a mode', ['Read', 'Write', 'Add', 'Modify'])
    mode = mode.lower()
    if mode == 'read':
        read_file(file_path)
    elif mode == 'write':
        write_file(file_path)
    elif mode == 'add':
        add_file(file_path)
    elif mode == 'modify':
        modify_file(file_path)
    else:
        raise RuntimeError('Invalid option {}'.format(mode))
예제 #10
0
파일: 2B.py 프로젝트: etscrivner/dse
def add_file(file_path):
    """Go through file line-by-line and ask for additions after given line.

    Arguments:
        file_path(str): The path to the file
    """
    numbers = io.read_numbers_from_file(file_path)
    output_file = prompt_for_output_file(file_path)

    # Go through each number one at a time
    results = []
    for idx, each in enumerate(numbers):
        # Display the results up to this point
        if results:
            print 'Numbers So Far:'
            for num in results:
                print num
        print 'Next number:'
        print each

        # Get the choice
        choice = io.choose_from_list('What would you like to do:', ['Keep', 'Add Number After', 'Keep Rest'])
        choice = choice.lower()
        if choice == 'keep':
            results.append(each)
        elif choice == 'add number after':
            # Get the new number and add it to the list
            results.append(each)
            number = io.get_and_confirm_input("New number: ")
            results.append(float(number))
        elif choice == 'keep rest':
            # Add remaining numbers to results and exit loop
            results += numbers[idx:]
            break

    # Write the updated numbers to the output file
    io.write_numbers_to_file(output_file, results)
    print 'Results written to', output_file
예제 #11
0
파일: 4B.py 프로젝트: etscrivner/dse
def write_file(file_path):
    """Requests a series of numerical inputs and writes them to the file.

    Arguments:
        file_path(basestring): The path to the file
    """
    if os.path.isfile(file_path):
        should_overwrite = io.yes_no_prompt(
            'File {} exists. Overwrite?'.format(file_path))
        # If the file shouldn't be overwritten, abort
        if not should_overwrite:
            enter_different_file = io.yes_no_prompt(
                'Would you like to enter a different file name?')
            if enter_different_file:
                file_path = io.prompt_valid_file_name('New file name: ')
                write_file(file_path)
            sys.exit('Aborting. Not overwriting existing file.')

    if not os.path.exists(os.path.dirname(file_path)):
        print 'ERROR: Directory for file {} does not exist'.format(file_path)
        io.prompt_try_again_or_abort()
        file_path = io.prompt_valid_file_name('New file name: ')
        write_file(file_path)

    total_num_entries = io.get_and_confirm_input(
        'How many numbers will you enter: ')
    total_num_entries = int(total_num_entries)

    num_entries_given = 0

    with open(file_path, 'w') as wfile:
        while num_entries_given < total_num_entries:
            value = io.get_and_confirm_float(
                'Entry #{}: '.format(num_entries_given + 1))
            value = float(value)
            wfile.write('{}\n'.format(value))
            num_entries_given += 1