brilliant_moves

EditFile.py

Feb 6th, 2015
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. #!/usr/bin/python
  2. #EditFile.py
  3. #Python 2.7
  4. #Edit contents of text file
  5. #Chris Clarke
  6. #21.08.2014
  7.  
  8. import os
  9. import sys
  10.  
  11. def getPath():
  12.    path = raw_input("Enter name of directory your file is in: ")
  13.    print os.listdir(path)
  14.    os.chdir(path)
  15.  
  16. getPath()
  17. filename = raw_input("Enter name of text file to open: ")
  18. lines = []
  19. try:
  20.    with open(filename) as f:
  21.       for line in f:
  22.          print '\n', line
  23.          print "For current line, please choose:"
  24.          choice = raw_input("edit, insert, append, delete? <return> = nextline: ")
  25.          choice = choice.lower() # convert to lower case
  26.          if choice in {'edit', 'ed', 'e'}:
  27.             newline = raw_input("Edit: type new line> ")
  28.             lines += newline+"\n"
  29.          elif choice in {'insert','ins', 'in', 'i'}:
  30.             newline = raw_input("Insert (add before): type new line> ")
  31.             lines += newline+"\n"
  32.             lines += line
  33.          elif choice in {'append', 'app', 'ap', 'a'}:
  34.             lines += line
  35.             newline = raw_input("Append (add after): type new line> ")
  36.             lines += newline+"\n"
  37.          elif choice in {'delete', 'del', 'd'}:
  38.             print "Line deleted."
  39.          else:
  40.             lines += line
  41. except IOError:
  42.    print "Unable to open file."
  43.    sys.exit(1)
  44. else:
  45.    f.close()
  46.  
  47. try:
  48.    with open(filename, 'w') as f:
  49.       for line in lines:
  50.          f.write(line),
  51. except IOError:
  52.    print "Couldn't write to file!"
  53. else:
  54.    print "File {0} saved.".format(filename)
  55.    f.close()
Advertisement
Add Comment
Please, Sign In to add comment