示例#1
0
from sys import argv
from os.path import exists
from helper_functions import append_txt

if len(argv) == 3:
    script, from_file, to_file = argv
else:
    from_file = raw_input("What file do you want to copy? ")
    to_file = raw_input("What do you want to call the copy? ")

if exists(append_txt(from_file)):
    open(append_txt(to_file), 'w').write(open(append_txt(from_file)).read())
    print "Alright, all done."
else:
    print "FAILED: file doesn't exist."
        else:
            print "You've chosen the last line"
    else:
        return "exit()"
    text = raw_input("What do you want to write? ")
    if text == exit_command:
        return "exit()"
    return {"line": line_number, "text": text}


if len(argv) >= 2:
    filename = argv[1]
else:
    filename = raw_input("What would you like to call the file? ")

filename = append_txt(filename)
if exists(filename):
    # file.read() returns back string, so need to make it an array and indexable
    # Don't use file.readline() because that only works with r or a+ modes
    # And in r mode you can't write, in a+ mode you can't overwrite
    file_content = open(filename).read().split("\n")
    print "\n", filename, " currently contains:"
    for idx, line in enumerate(file_content):
        print idx + 1, ": ", line
else:
    print "\nCreating file ", filename
    file_content = []

print "\nStop at any time by entering 'exit()'"
commands = get_input(file_content)
while commands != exit_command:
"""
Practice reading and writing files
"""
from sys import argv
from os.path import exists
from helper_functions import append_txt

if len(argv) == 2:
    script, filename = argv
else:
    filename = append_txt(raw_input("What file do you want to open? "))

file_exists = exists(filename)
if file_exists:
    txt = open(filename)
    print "\nHere's your file %r:" % filename
    print txt.read()
    txt.close()
else:
    print "\nThis will be a new file!"
    print "If you don't want that, hit CTRL-C (^C)."

# r+ writes like insert
# a+ reads from end of file, writes to end of file, creates file if it doesn't exist
# w+ will overwrite and read from end of file (file overwritten upon open)
# r, w, and a will only do their respective tasks
if file_exists:
    open_type = raw_input("Do you want to overwrite (w) or append (a)? ").lower()
    if open_type != "w" and open_type != "a" and open_type != "r":
        print "Not a valid option. We're going to append"
        open_type = "a"