Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- #EditFile.py
- #Python 2.7
- #Edit contents of text file
- #Chris Clarke
- #21.08.2014
- import os
- import sys
- def getPath():
- path = raw_input("Enter name of directory your file is in: ")
- print os.listdir(path)
- os.chdir(path)
- getPath()
- filename = raw_input("Enter name of text file to open: ")
- lines = []
- try:
- with open(filename) as f:
- for line in f:
- print '\n', line
- print "For current line, please choose:"
- choice = raw_input("edit, insert, append, delete? <return> = nextline: ")
- choice = choice.lower() # convert to lower case
- if choice in {'edit', 'ed', 'e'}:
- newline = raw_input("Edit: type new line> ")
- lines += newline+"\n"
- elif choice in {'insert','ins', 'in', 'i'}:
- newline = raw_input("Insert (add before): type new line> ")
- lines += newline+"\n"
- lines += line
- elif choice in {'append', 'app', 'ap', 'a'}:
- lines += line
- newline = raw_input("Append (add after): type new line> ")
- lines += newline+"\n"
- elif choice in {'delete', 'del', 'd'}:
- print "Line deleted."
- else:
- lines += line
- except IOError:
- print "Unable to open file."
- sys.exit(1)
- else:
- f.close()
- try:
- with open(filename, 'w') as f:
- for line in lines:
- f.write(line),
- except IOError:
- print "Couldn't write to file!"
- else:
- print "File {0} saved.".format(filename)
- f.close()
Advertisement
Add Comment
Please, Sign In to add comment