small medium large xlarge



Reading and Writing Files


filename = input('Which file would you like to back-up? ')
new_filename = filename + '.bak'
backup = open(new_filename, 'w')

for line in open(filename):



alkaline_metals = []
for line in open('alkaline_metals.txt'):
    alkaline_metals.append(line.strip().split(' '))


You could read the file contents into a data structure, such as a list, and then iterate over the list from end (last line) to beginning (first line).


def process_file(reader):
    """ (file open for reading) -> NoneType

    Read and print the data from reader, which must start with a single
    description line, then a sequence of lines beginning with '#', then a
    sequence of data.

    # Find and print the first piece of data.
    line = skip_header(reader).strip()

    # Read the rest of the data.



import time_series

def smallest_value_skip(reader):
    """ (file open for reading) -> NoneType

    Read and process reader, which must start with a time_series header.
    Return the smallest value after the header.  Skip missing values, which
    are indicated with a hyphen.

    line = time_series.skip_header(reader).strip()

    # Now line contains the first data value; this is also the smallest value
    # found so far, because it is the only one we have seen.
    smallest = int(line)

    for line in reader:
        line = line.strip()
        if line == '-':

        value = int(line)
        smallest = min(smallest, value)

    return smallest

if __name__ == '__main__':
    with open('hebron.txt', 'r') as input_file:


def read_molecule(reader):
    """ (file open for reading) -> list or NoneType

    Read a single molecule from reader and return it, or return None to signal
    end of file.  The first item in the result is the name of the compound;
    each list contains an atom type and the X, Y, and Z coordinates of that

    # If there isn't another line, we're at the end of the file.
    line = reader.readline()
    if not line:
        return None

    # Name of the molecule: "COMPND   name" 
    key, name = line.split()

    # Other lines are either "END" or "ATOM num atom_type x y z" 
    molecule = [name]
    reading = True

    serial_number = 1
    while reading:
        line = reader.readline()
        if line.startswith('END'):
            reading = False
            key, num, atom_type, x, y, z = line.split()
            if int(num) != serial_number:
                print('Expected serial number {0}, but got {1}'.format(
                    serial_number, num))
            molecule.append([atom_type, x, y, z])
            serial_number += 1

    return molecule
Page History
  • V6: Jennifer Campbell [about 3 years ago]
  • V5: Jennifer Campbell [about 3 years ago]
  • V4: Jennifer Campbell [about 3 years ago]
  • V3: Jennifer Campbell [about 3 years ago]
  • V2: Jennifer Campbell [about 3 years ago]
  • V1: Jason Montojo [over 3 years ago]